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
feat(imagemap): contrast-weighted cluster labels and DFN2B CLIP default
Lincoln Steinc2d3f55e29fc
diff --git a/docs/src/generated/settings.json b/docs/src/generated/settings.jsonindex 337a9df480..e05f773a4b 100644--- a/docs/src/generated/settings.json+++ b/docs/src/generated/settings.json@@ -866,7 +866,7 @@},{"category": "IMAGE INDEX",- "default": "clip-vit-large-patch14",+ "default": "DFN2B-CLIP-ViT-L-14-39B","description": "Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.","env_var": "INVOKEAI_IMAGE_INDEX_MODEL","literal_values": [],diff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.pyindex 64d3f87d69..5bfe0fe936 100644--- a/invokeai/app/services/config/config_default.py+++ b/invokeai/app/services/config/config_default.py@@ -261,7 +261,7 @@ class InvokeAIAppConfig(BaseSettings):# IMAGE INDEXimage_index_enabled: bool = Field(default=False, description="Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.")- image_index_model: str = Field(default="clip-vit-large-patch14", description="Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.")+ image_index_model: str = Field(default="DFN2B-CLIP-ViT-L-14-39B", description="Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.")image_index_device: Optional[str] = Field(default=None, description="Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.")image_index_batch_size: int = Field(default=8, gt=0, description="Number of images embedded per batch by the image index worker.")diff --git a/invokeai/app/services/image_index/cluster_labels.py b/invokeai/app/services/image_index/cluster_labels.pyindex 090f37d5c9..e12a6d9672 100644--- a/invokeai/app/services/image_index/cluster_labels.py+++ b/invokeai/app/services/image_index/cluster_labels.py@@ -93,6 +93,16 @@ def ensemble_phrase_embeddings(embed_texts, phrases: list[str], batch_size: intreturn (matrix / norms).astype(EMBEDDING_DTYPE)+# Weight of the corpus-mean term in cluster label ranking (see label_clusters).+# 0 is raw cosine (hub phrases win everywhere); 1 is full mean-centering (no+# floor — content-orthogonal phrases can win on corpus anti-alignment, and two+# clusters rank by exact negations of each other). 0.75 demotes hub phrases+# even when clusters share a large common component, while a phrase must still+# beat the winner's 0.25 * raw-cosine residue to displace a strong content+# match.+_CORPUS_CONTRAST_WEIGHT = 0.75++def label_clusters(cluster_labels: np.ndarray,image_embeddings: np.ndarray,@@ -102,6 +112,22 @@ def label_clusters() -> dict[int, dict]:"""Top-k vocabulary labels for every non-noise cluster.+ Phrases are ranked by ``cos(phrase, centroid) - W * cos(phrase, corpus+ mean)``, not by raw cosine alone. Raw cosine has a hubness problem: generic+ phrases (color words especially) sit close to the mean direction of any+ image collection, and averaging a cluster pulls its centroid toward that+ same mean — so hub phrases win everywhere regardless of what the cluster+ is about. The corpus term cancels that shared component. It is a weighted+ blend rather than full mean-centering because pure contrast has no floor:+ with the centroid's own cosine fully cancelled, a phrase orthogonal to the+ cluster's content can win on corpus anti-alignment alone (with exactly two+ clusters the centered directions are exact negations of each other, so one+ cluster is always labeled by whatever anti-correlates with the other). The+ ``1 - W`` residue of raw cosine keeps the winner tied to what the cluster+ actually contains, and makes degenerate contrast safe by construction: a+ centroid equal to the corpus mean scores every phrase at ``(1 - W) * raw``,+ which ranks identically to raw cosine — no fallback threshold needed.+Args:cluster_labels: (N,) DBSCAN labels, row-aligned with image_embeddings.image_embeddings: (N, D) L2-normalized image embeddings.@@ -111,9 +137,17 @@ def label_clusters(Returns:{cluster_id: {"label": str, "alternates": [str], "score": float}};- noise (-1) is omitted.+ noise (-1) is omitted. "score" is the raw cosine between the chosen+ phrase and the unit centroid, so it stays comparable across clusters."""results: dict[int, dict] = {}+ clustered = image_embeddings[cluster_labels >= 0]+ corpus_scores: np.ndarray | None = None+ if clustered.shape[0]:+ corpus_mean = clustered.mean(axis=0)+ corpus_norm = np.linalg.norm(corpus_mean)+ if corpus_norm > 0:+ corpus_scores = vocab_embeddings @ (corpus_mean / corpus_norm).astype(vocab_embeddings.dtype)for cluster_id in sorted({int(label) for label in cluster_labels if label >= 0}):members = image_embeddings[cluster_labels == cluster_id]if members.shape[0] == 0:@@ -122,14 +156,18 @@ def label_clusters(norm = np.linalg.norm(centroid)if norm == 0:continue- centroid = centroid / norm- scores = vocab_embeddings @ centroid.astype(vocab_embeddings.dtype)+ unit_centroid = (centroid / norm).astype(vocab_embeddings.dtype)+ raw_scores = vocab_embeddings @ unit_centroid+ if corpus_scores is None:+ scores = raw_scores+ else:+ scores = raw_scores - _CORPUS_CONTRAST_WEIGHT * corpus_scorescount = min(top_k, len(vocabulary))top = np.argpartition(-scores, count - 1)[:count]top = top[np.argsort(-scores[top])]results[cluster_id] = {"alternates": [vocabulary[index] for index in top[1:]],"label": vocabulary[top[0]],- "score": float(scores[top[0]]),+ "score": float(raw_scores[top[0]]),}return resultsdiff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.pyindex ee5c53fa32..d4abb4c012 100644--- a/invokeai/app/services/image_index/image_index_default.py+++ b/invokeai/app/services/image_index/image_index_default.py@@ -1241,12 +1241,19 @@ class ImageIndexService(ImageIndexServiceBase):return (f"Image indexing is enabled, but the installed model named '{model_name}' is of type "f"'{types}', not a CLIP Vision or SigLIP image encoder. Install the image-encoder model of "- "the same name (for the default, the 'CLIP ViT-L Image Encoder' starter model from source "- "'InvokeAI/clip-vit-large-patch14'). The image index will not be updated."+ "the same name (for the default, the 'DFN2B CLIP ViT-L Image Encoder' starter model from "+ "source 'apple/DFN2B-CLIP-ViT-L-14-39B'). The image index will not be updated.")+ # Upgrades hit this branch: installs that never set image_index_model+ # adopt the new default name, which is not installed yet. Name both+ # ways out — installing the new starter (full re-index) or pinning the+ # previous default to keep the embeddings already computed under it.return (f"Image indexing is enabled but the embedding model '{model_name}' is not installed "- "(expected a CLIP Vision or SigLIP model). The image index will not be updated."+ "(expected a CLIP Vision or SigLIP model). For the default, install the "+ "'DFN2B CLIP ViT-L Image Encoder' starter model from source 'apple/DFN2B-CLIP-ViT-L-14-39B' "+ "(the gallery will re-index). To keep embeddings computed under the previous default instead, "+ "set image_index_model: clip-vit-large-patch14. The image index will not be updated.")def _resolve_model_config(self, model_name: str) -> Optional["AnyModelConfig"]:diff --git a/invokeai/backend/model_manager/starter_models.py b/invokeai/backend/model_manager/starter_models.pyindex 30c8496923..748f08737d 100644--- a/invokeai/backend/model_manager/starter_models.py+++ b/invokeai/backend/model_manager/starter_models.py@@ -81,7 +81,21 @@ clip_vit_l_image_encoder = StarterModel(name="clip-vit-large-patch14",base=BaseModelType.Any,source="InvokeAI/clip-vit-large-patch14",- description="CLIP VIT-L Image Encoder (used by the imagemap index) ~1.7GB",+ description="CLIP VIT-L Image Encoder ~1.7GB",+ type=ModelType.CLIPVision,+)+# Apple's DFN2B CLIP: same ViT-L-14 architecture as the model above, much+# stronger zero-shot weights (Data Filtering Networks, 39B samples seen). The+# imagemap index default: raw-cosine cluster labeling needs an encoder whose+# text/image geometry separates well, and the OpenAI weights let generic "hub"+# phrases (color words) outscore content phrases. The repo also carries an+# open_clip copy of the weights, which the HF file filter cannot distinguish+# from the transformers copy — hence the doubled download size in the blurb.+dfn2b_clip_vit_l_image_encoder = StarterModel(+ name="DFN2B-CLIP-ViT-L-14-39B",+ base=BaseModelType.Any,+ source="apple/DFN2B-CLIP-ViT-L-14-39B",+ description="DFN2B CLIP ViT-L Image Encoder (used by the imagemap index) ~3.4GB download",type=ModelType.CLIPVision,)# endregion@@ -2429,6 +2443,7 @@ STARTER_MODELS: list[StarterModel] = [t5_gguf_q6_k_encoder,clip_l_encoder,clip_vit_l_image_encoder,+ dfn2b_clip_vit_l_image_encoder,siglip,flux_redux,llava_onevision,diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex e3bce43e61..5de1f2b11a 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -51656,7 +51656,7 @@"type": "string","title": "Image Index Model","description": "Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.",- "default": "clip-vit-large-patch14"+ "default": "DFN2B-CLIP-ViT-L-14-39B"},"image_index_device": {"anyOf": [diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex 72c545fd01..d48262a56c 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -20266,7 +20266,7 @@ export type components = {/*** Image Index Model* @description Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.- * @default clip-vit-large-patch14+ * @default DFN2B-CLIP-ViT-L-14-39B*/image_index_model?: string;/**diff --git a/tests/app/services/image_index/test_cluster_labels.py b/tests/app/services/image_index/test_cluster_labels.pyindex 5f094d3959..dfb3db9430 100644--- a/tests/app/services/image_index/test_cluster_labels.py+++ b/tests/app/services/image_index/test_cluster_labels.py@@ -53,5 +53,78 @@ def test_label_clusters_picks_nearest_phrase_per_cluster() -> None:assert set(labels) == {0, 1}assert labels[0]["label"] == "x-things"assert labels[1]["label"] == "y-things"- assert labels[0]["alternates"] == ["y-things"]+ # The corpus-contrast term demotes the other cluster's phrase below the+ # neutral one.+ assert labels[0]["alternates"] == ["z-things"]assert 0 < labels[0]["score"] <= 1.0+++def _unit(v: list[float]) -> np.ndarray:+ arr = np.array(v, dtype=np.float32)+ return arr / np.linalg.norm(arr)+++def test_label_clusters_demotes_hub_phrases() -> None:+ # A "hub" phrase aligned with the shared direction of every cluster wins+ # raw cosine everywhere; the corpus-contrast term must surface the+ # distinctive axis.+ vocab = ["hub-phrase", "x-things", "y-things"]+ vocab_embeddings = np.stack([_unit([1, 1, 1]), _unit([0, 1, 0]), _unit([0, 0, 1])])+ # Two clusters sharing a dominant common component, differing on axes 1/2.+ image_embeddings = np.stack([_unit([1, 0.3, 0]), _unit([1, 0.4, 0]), _unit([1, 0, 0.3]), _unit([1, 0, 0.4])])+ cluster_labels = np.array([0, 0, 1, 1])++ # Sanity: without the contrast term, the hub phrase beats both distinctive+ # phrases.+ raw = vocab_embeddings @ _unit(list(image_embeddings[:2].mean(axis=0)))+ assert raw[0] > raw[1]++ labels = label_clusters(cluster_labels, image_embeddings, vocab, vocab_embeddings, top_k=1)++ assert labels[0]["label"] == "x-things"+ assert labels[1]["label"] == "y-things"+++def test_label_clusters_single_cluster_ranks_by_raw_cosine() -> None:+ # With one cluster the centroid equals the corpus mean, so the contrast+ # term subtracts the same multiple of every phrase's raw score — the+ # ranking must degrade to plain raw cosine, not to amplified noise.+ vocab = ["x-things", "y-things"]+ vocab_embeddings = np.eye(2, dtype=np.float32)+ image_embeddings = np.array([[1, 0], [0.9, 0.1]], dtype=np.float32)+ cluster_labels = np.array([0, 0])++ labels = label_clusters(cluster_labels, image_embeddings, vocab, vocab_embeddings, top_k=1)++ assert labels[0]["label"] == "x-things"+ assert 0 < labels[0]["score"] <= 1.0+++def test_label_clusters_keeps_shared_content_label_for_similar_clusters() -> None:+ # Two clusters of near-identical content: pure mean-centering would rank+ # each by the exact negation of the other (junk phrases win); the blended+ # score must keep the phrase that describes both.+ vocab = ["cat", "junk-up", "junk-down"]+ vocab_embeddings = np.stack([_unit([1, 0, 0]), _unit([0, 1, 0]), _unit([0, -1, 0])])+ image_embeddings = np.stack([_unit([1, 0.05, 0]), _unit([1, 0.06, 0]), _unit([1, -0.05, 0]), _unit([1, -0.06, 0])])+ cluster_labels = np.array([0, 0, 1, 1])++ labels = label_clusters(cluster_labels, image_embeddings, vocab, vocab_embeddings, top_k=1)++ assert labels[0]["label"] == "cat"+ assert labels[1]["label"] == "cat"+++def test_label_clusters_dominant_cluster_keeps_own_content_label() -> None:+ # A cluster holding most of the corpus sits nearly on the corpus mean, so+ # pure centering would label it by whatever anti-correlates with the small+ # clusters; the blend must keep its own content phrase on top.+ vocab = ["dog", "anti-minority"]+ vocab_embeddings = np.stack([_unit([1, 0, 0]), _unit([0.5, -0.6, -0.6])])+ dominant = [_unit([1, 0.05, 0]) if i % 2 else _unit([1, -0.05, 0]) for i in range(8)]+ image_embeddings = np.stack(dominant + [_unit([0.3, 1, 0]), _unit([0.3, 0, 1])])+ cluster_labels = np.array([0] * 8 + [1, 2])++ labels = label_clusters(cluster_labels, image_embeddings, vocab, vocab_embeddings, top_k=1)++ assert labels[0]["label"] == "dog"diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.pyindex e384ba3e05..b49431be82 100644--- a/tests/app/services/image_index/test_image_index_service.py+++ b/tests/app/services/image_index/test_image_index_service.py@@ -309,7 +309,7 @@ def test_model_not_installed_message_flags_same_name_wrong_type() -> None:)message = service._model_not_installed_message("clip-vit-large-patch14")assert "clip_embed" in message- assert "InvokeAI/clip-vit-large-patch14" in message+ assert "apple/DFN2B-CLIP-ViT-L-14-39B" in messageservice._invoker.services.model_manager.store.search_by_attr = lambda model_name=None: []message = service._model_not_installed_message("clip-vit-large-patch14")