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: keep cluster labelling off the request path and out of the scene rebuild
Lincoln Stein8cd0070a9901
diff --git a/invokeai/app/api/routers/image_map.py b/invokeai/app/api/routers/image_map.pyindex 2384b95a54..6a642d1dee 100644--- a/invokeai/app/api/routers/image_map.py+++ b/invokeai/app/api/routers/image_map.py@@ -18,6 +18,7 @@ from invokeai.app.services.image_index.image_index_common import ImageIndexStatufrom invokeai.app.services.image_index.projection import (DEFAULT_CLUSTER_MIN_SAMPLES,MAX_CLUSTERED_POINTS,+ MIN_BUDGETED_EPS,cluster_at_eps,compute_clusters,resolve_cluster_eps,@@ -101,7 +102,13 @@ class ImageMapRefreshResponse(BaseModel):ClusterEpsQuery = Query(default=None,- ge=0.01,+ # Floored at what the resolver itself can produce, not at a round number:+ # `_shrink_eps_to_pair_budget` walks down to MIN_BUDGETED_EPS on a map with+ # near-coincident coordinates (duplicate generations project to the same+ # spot), and /points reports that value as `cluster_eps` for the client to+ # pass back here. A higher bound rejects the server's own output, and the+ # client treats the 422 as "no labels" with nothing logged anywhere.+ ge=MIN_BUDGETED_EPS,le=2.0,description="DBSCAN eps for clustering. Defaults to an adaptive value derived from the projection's ""k-distance distribution. Clamped server-side relative to the projection's coordinate span.",@@ -725,6 +732,14 @@ async def get_image_map_cluster_labels(# a label set whose visible_hash does not match its points.services.logger.exception(f"Image map: clustering failed for user '{user_id}'; serving no labels")return {}, visible_hash+ # Nothing clustered, nothing to label. Worth checking before the gather+ # below: above MAX_CLUSTERED_POINTS every id is -1 by design, and on a+ # gallery that large the fancy-index would copy gigabytes purely to+ # hand label_clusters a set of noise rows it discards.+ clustered = cluster_ids >= 0+ if not clustered.any():+ return {}, visible_hash+cluster_by_name = dict(zip(visible_names, cluster_ids, strict=True))# The accessible matrix comes from the same LRU the search endpoint# uses — this endpoint fires after every points refresh, and a full@@ -733,7 +748,13 @@ async def get_image_map_cluster_labels(None if is_admin else user_id)row_by_name = {name: index for index, name in enumerate(accessible_names)}- found_names = [name for name in visible_names if name in row_by_name]+ # Noise rows are excluded here rather than inside label_clusters: they+ # contribute to no centroid, so gathering them only widens the copy.+ found_names = [+ name+ for name, is_clustered in zip(visible_names, clustered, strict=True)+ if is_clustered and name in row_by_name+ ]if not found_names:return {}, visible_hashembeddings = accessible_matrix[[row_by_name[name] for name in found_names]]diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.pyindex ecf707687e..b366969bcd 100644--- a/invokeai/app/services/image_index/image_index_default.py+++ b/invokeai/app/services/image_index/image_index_default.py@@ -1,3 +1,4 @@+import osimport threadingfrom pathlib import Pathfrom queue import Empty, Queue@@ -73,6 +74,26 @@ def _normalize_query_vector(vector: np.ndarray) -> np.ndarray:return (vector / norm).astype(EMBEDDING_DTYPE)+def _normalize_batch(matrix: np.ndarray) -> np.ndarray:+ """L2-normalize each row, zeroing the ones that cannot be normalized.++ Shares `_normalize_query_vector`'s float64 norm — a float32 sum of squares+ under/overflows inside the range these encoders produce — but not its+ refusal. A single query is worth failing loudly; a batch is not. The+ vocabulary build sends ~11,700 phrases through here, and aborting all of+ them over one degenerate row would discard minutes of encoder work, raise+ past the caller's error handling as a 500, and (nothing having been cached)+ do it all again on the next request.++ A zeroed row scores 0 against everything, so the phrase simply never wins a+ label — which is what a meaningless embedding should do.+ """+ norms = np.linalg.norm(matrix.astype(np.float64), axis=1, keepdims=True)+ usable = np.isfinite(norms) & (norms > 0)++ return np.where(usable, matrix / np.where(usable, norms, 1.0), 0.0).astype(EMBEDDING_DTYPE)++def warm_up_attention(config: "InvokeAIAppConfig", logger: "Logger") -> None:"""Run one tiny scaled_dot_product_attention call while the process is still single-threaded.@@ -163,6 +184,14 @@ class ImageIndexService(ImageIndexServiceBase):# Lazily-loaded (tokenizer, text_model, is_siglip); None until first text search.self._text_encoder: Optional[tuple[Any, Any, bool]] = Noneself._text_encoder_lock = threading.Lock()+ # 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+ # points refresh, forever.+ self._vocab_failure: Optional[Exception] = None+ # Set by a labels request, serviced on the worker: the build is minutes+ # of encoder work and must never run on a request thread.+ self._vocab_build_requested = threading.Event()# Guards the lazy _processor/_cpu_model init: embed_image runs on# request threads concurrently with the indexer worker.self._vision_init_lock = threading.Lock()@@ -221,13 +250,32 @@ class ImageIndexService(ImageIndexServiceBase):outputs = model(**inputs)embeddings = outputs.pooler_output if is_siglip else outputs.text_embedsmatrix = embeddings.float().cpu().numpy()- # Row by row through the shared guard rather than a bulk float32 divide:- # that computes the norm in float64 and refuses a zero or non-finite one- # instead of quietly emitting a NaN row, which would go on to score NaN- # against everything it is compared with.- return np.stack([_normalize_query_vector(row) for row in matrix])+ return _normalize_batch(matrix)def get_vocab_embeddings(self) -> tuple[list[str], np.ndarray]:+ """The phrase-embedding matrix for cluster labelling.++ Never builds it: a first run embeds ~1700 phrases x 7 templates through+ a CPU text tower, which takes minutes. Callers run on the event loop's+ shared executor, so blocking there — worse, blocking there while holding+ `_vocab_lock` — starves every other `asyncio.to_thread` in the app,+ `/points` and image search included. The build is handed to the index+ worker instead and this raises until it lands.+ """+ with self._vocab_lock:+ if self._vocab_cache is not None:+ return self._vocab_cache+ if self._vocab_failure is not None:+ raise self._vocab_failure+ if self._invoker is None or self._model_id is None:+ raise TextSearchUnavailableError("The image index is not running")++ self._vocab_build_requested.set()++ raise TextSearchUnavailableError("Cluster labels are still being prepared; try again shortly")++ def _build_vocab_embeddings(self) -> None:+ """Build and cache the phrase embeddings. Index-worker thread only."""from invokeai.app.services.image_index.cluster_labels import (ensemble_phrase_embeddings,load_vocabulary,@@ -235,10 +283,10 @@ class ImageIndexService(ImageIndexServiceBase):)with self._vocab_lock:- if self._vocab_cache is not None:- return self._vocab_cache+ if self._vocab_cache is not None or self._vocab_failure is not None:+ returnif self._invoker is None or self._model_id is None:- raise TextSearchUnavailableError("The image index is not running")+ returnvocabulary = load_vocabulary()fingerprint = vocab_fingerprint(vocabulary)@@ -249,23 +297,41 @@ class ImageIndexService(ImageIndexServiceBase):if cache_path.exists():try:- cached = np.load(cache_path, allow_pickle=False)- if str(cached["fingerprint"]) == fingerprint:- self._vocab_cache = (vocabulary, cached["embeddings"].astype(EMBEDDING_DTYPE))- return self._vocab_cache+ # Closed explicitly: np.load returns a lazily-read NpzFile+ # holding the zip handle open, and the rewrite below+ # truncates this very file on a fingerprint mismatch.+ with np.load(cache_path, allow_pickle=False) as cached:+ if str(cached["fingerprint"]) == fingerprint:+ self._vocab_cache = (vocabulary, cached["embeddings"].astype(EMBEDDING_DTYPE))++ if self._vocab_cache is not None:+ returnexcept Exception:self._invoker.services.logger.warning("Discarding unreadable cluster vocabulary cache")# First run for this model: embedding ~1700 phrases x 7 templates- # takes tens of seconds — hence the disk cache.- embeddings = ensemble_phrase_embeddings(self._embed_texts, vocabulary)+ # takes minutes — hence the disk cache.+ try:+ embeddings = ensemble_phrase_embeddings(self._embed_texts, vocabulary)+ except Exception as e:+ # 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)++ return+try:cache_path.parent.mkdir(parents=True, exist_ok=True)- np.savez(cache_path, embeddings=embeddings, fingerprint=np.str_(fingerprint))+ # Written aside and renamed: two processes sharing a db_dir can+ # first-run at once, and a kill mid-write would otherwise leave+ # a truncated archive that costs another full re-embed.+ staging_path = cache_path.with_name(f"{cache_path.name}.{os.getpid()}.tmp")+ np.savez(staging_path, embeddings=embeddings, fingerprint=np.str_(fingerprint))+ os.replace(staging_path, cache_path)except Exception:self._invoker.services.logger.warning(f"Could not write cluster vocabulary cache to {cache_path}")self._vocab_cache = (vocabulary, embeddings)- return self._vocab_cachedef _get_text_encoder(self) -> tuple[Any, Any, bool]:with self._text_encoder_lock:@@ -567,6 +633,13 @@ class ImageIndexService(ImageIndexServiceBase):# abandoned thread writes the database and emits an event# after the app believes the service is down.break+ if self._vocab_build_requested.is_set():+ # Cleared first: a request arriving mid-build wants the+ # result of a build that is already covering it, and+ # _build_vocab_embeddings is a no-op once one has landed.+ self._vocab_build_requested.clear()+ self._build_vocab_embeddings()+ continueprojection_job = self._next_projection_job()if projection_job is not None:self._process_projection(*projection_job)diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.tsindex 67ef4a7b2a..6cf5fd1b59 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts@@ -143,7 +143,42 @@ const areLabelMapsEqual = (left: Record<string, string> | null, right: Record<st* label response for a different projection — or one overtaken by a newer* request — is discarded rather than mislabeling clusters.*/+/**+ * Whether the map is currently showing labels. Pushed down from the widget's+ * toggle so the request can be skipped outright: labelling costs the server a+ * DBSCAN pass over the visible set, an embedding gather and a 1675-way matmul+ * per cluster, and it is precisely the people with galleries large enough to+ * feel that who turn the labels off.+ */+let clusterLabelsEnabled = true;++export const setClusterLabelsEnabled = (enabled: boolean): void => {+ if (enabled === clusterLabelsEnabled) {+ return;+ }++ clusterLabelsEnabled = enabled;++ if (!enabled) {+ // Bump the sequence so a request already in flight cannot land after this.+ labelsSequence += 1;+ imageMapStore.patchSnapshot({ clusterLabels: null });++ return;+ }++ const { data } = imageMapStore.getSnapshot();++ if (data) {+ refreshClusterLabels(data);+ }+};+const refreshClusterLabels = (data: ImageMapPoints): void => {+ if (!clusterLabelsEnabled) {+ return;+ }+if (data.state !== 'ready') {// Nothing to label; a disabled index would 409 on every refresh. Bump the// sequence so an in-flight labels response cannot repopulate the labelsdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsxindex 9e29d24cfb..d0d2244d7e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx@@ -216,10 +216,10 @@ const ImageMapPlot = ({}}- const layout = buildMapLayout(- initialRanges,- buildClusterAnnotations(points, showClusterLabels ? clusterLabels : null)- );+ // Annotations are deliberately absent here: they are a layout concern, and+ // rebuilding the scene for them is what made labels arriving a second after+ // the points re-materialize every trace. See the relayout effect below.+ const layout = buildMapLayout(initialRanges);void Plotly.react(container, traces as Plotly.Data[], layout, {displayModeBar: false,@@ -309,7 +309,7 @@ const ImageMapPlot = ({return () => {disposed = true;};- }, [clusterLabels, points, selectCluster, selectImage, showClusterLabels]);+ }, [points, selectCluster, selectImage]);// Highlight overlay: the gallery's multi-selection, restyled in place.useEffect(() => {@@ -399,6 +399,25 @@ const ImageMapPlot = ({}}, [plotRevision, points, selectedImageName]);+ // Labels arrive about a second after the points they annotate. Applying them+ // with `relayout` rather than through the scene effect keeps that from+ // re-materializing every coordinate array — and, more visibly, from resetting+ // the highlight and current-image traces to empty, which made the gold marker+ // and the multi-select highlight blink off and back on with every refresh.+ useEffect(() => {+ const container = containerRef.current as PlotElement | null;++ if (!container || points === null || !container.data) {+ return;+ }++ swallow(+ Plotly.relayout(container, {+ annotations: buildClusterAnnotations(points, showClusterLabels ? clusterLabels : null),+ })+ );+ }, [clusterLabels, plotRevision, points, showClusterLabels]);+// Custom zoom handlers + container size tracking, attached once for the// plot's lifetime; plotly does not observe its container.useEffect(() => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsxindex accee59981..b1fdb6e70e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx@@ -2,7 +2,12 @@ import type { WidgetViewProps } from '@workbench/widgetContracts';import { Button, Center, Spinner, Stack, Text } from '@chakra-ui/react';import { getImageMapClickSelectsCluster, getImageMapShowClusterLabels } from '@workbench/image-map/imageMapSettings';-import { ensureImageMapLoaded, imageMapStore, refreshImageMapPoints } from '@workbench/image-map/imageMapStore';+import {+ ensureImageMapLoaded,+ imageMapStore,+ refreshImageMapPoints,+ setClusterLabelsEnabled,+} from '@workbench/image-map/imageMapStore';import { useWidgetValuesSelector } from '@workbench/WorkbenchContext';import { lazy, Suspense, useEffect } from 'react';@@ -37,6 +42,12 @@ export const ImageMapWidgetView = (_props: WidgetViewProps) => {ensureImageMapLoaded();}, []);+ // Pushed into the store so turning labels off stops the request, not just the+ // drawing of what it returns.+ useEffect(() => {+ setClusterLabelsEnabled(showClusterLabels);+ }, [showClusterLabels]);+// Checked before the plot: this is the canvas failing, not a fetch, so// re-mounting the plot would just fail again and render an empty box with no// way out. A successful refresh clears it and lets the plot retry.diff --git a/tests/app/routers/test_image_map.py b/tests/app/routers/test_image_map.pyindex 3e7e94397e..8f09a7956e 100644--- a/tests/app/routers/test_image_map.py+++ b/tests/app/routers/test_image_map.py@@ -844,6 +844,40 @@ def test_image_search_reports_an_encoder_fault_as_a_server_error(assert client.get("/api/v1/image_map/search", params={"image_name": "not-indexed.png"}).status_code == 500+def test_cluster_labels_skips_the_embedding_gather_when_nothing_clustered(+ monkeypatch, mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient+) -> None:+ # Above MAX_CLUSTERED_POINTS every id is -1 by design, and label_clusters+ # returns {} for that. Gathering the accessible rows first copies+ # len(visible) x D float32 for nothing — gigabytes on the large galleries+ # /points is written for, once per points refresh.+ from invokeai.app.services.image_index import image_index_default++ _seed_embedded_image(mock_invoker, "a.png")+ _seed_projection(mock_invoker, SYSTEM_USER_ID, ["a.png"], np.zeros((1, 2), dtype=np.float32))++ monkeypatch.setattr(+ "invokeai.app.api.routers.image_map.compute_clusters",+ lambda coords, eps=None, min_samples=None: np.full((coords.shape[0],), -1, dtype=np.int64),+ )++ gathered = []+ original = image_index_service.get_accessible_embeddings++ def _spy(scope_user):+ gathered.append(scope_user)++ return original(scope_user)++ monkeypatch.setattr(image_index_service, "get_accessible_embeddings", _spy)++ response = client.get("/api/v1/image_map/cluster_labels")++ assert response.status_code == 200+ assert response.json()["labels"] == {}+ assert gathered == [], "the accessible matrix was gathered for a fully-unclustered map"++def test_search_by_image_upload_returns_ranked_results(image_index_service: FakeImageIndexService, client: TestClient) -> None:diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.pyindex 942d0feb8b..7c11dadfb7 100644--- a/tests/app/services/image_index/test_image_index_service.py+++ b/tests/app/services/image_index/test_image_index_service.py@@ -1674,3 +1674,53 @@ def test_lazy_model_construction_takes_the_process_global_load_lock() -> None:assert "MODEL_LOAD_LOCK.write_lock()" in source, (f"{fn.__qualname__} patches torch globally without the process-global load lock")+++def test_vocab_embeddings_are_never_built_on_the_caller(service: ImageIndexService) -> None:+ # The build is minutes of encoder work and callers reach it through+ # asyncio.to_thread on the loop's shared executor. Blocking there — worse,+ # blocking there under _vocab_lock — starves every other to_thread in the+ # app, /points and image search included. The request only asks the worker.+ from invokeai.app.services.image_index.image_index_base import TextSearchUnavailableError++ service._invoker = SimpleNamespace() # type: ignore[assignment]+ service._model_id = MODEL_ID++ with pytest.raises(TextSearchUnavailableError, match="still being prepared"):+ service.get_vocab_embeddings()++ assert service._vocab_build_requested.is_set()+++def test_a_failed_vocabulary_build_is_not_retried_on_every_request(service: ImageIndexService) -> None:+ # A vision-only install has no text tower. Without remembering the failure,+ # every points refresh retries from_pretrained inside MODEL_LOAD_LOCK,+ # contending with generation's model loads for as long as the app runs.+ from invokeai.app.services.image_index.image_index_base import TextSearchUnavailableError++ service._vocab_failure = TextSearchUnavailableError("no text encoder") # type: ignore[assignment]++ with pytest.raises(TextSearchUnavailableError, match="no text encoder"):+ service.get_vocab_embeddings()++ # Not even queued: there is nothing for the worker to retry.+ assert not service._vocab_build_requested.is_set()+++def test_batch_normalization_zeroes_a_degenerate_row_instead_of_failing(service: ImageIndexService) -> None:+ # One bad row out of ~11,700 must not discard the whole vocabulary build:+ # that raises past the endpoint's handling as a 500 and, nothing having been+ # cached, repeats the full embed on the next request. A zeroed row scores 0+ # against everything, so the phrase simply never wins a label.+ from invokeai.app.services.image_index.image_index_default import _normalize_batch++ matrix = np.ones((3, DIM), dtype=np.float32)+ matrix[1] = 0.0+ matrix[2, 0] = np.inf++ normalized = _normalize_batch(matrix)++ assert np.isfinite(normalized).all()+ assert float(np.linalg.norm(normalized[0])) == pytest.approx(1.0, rel=1e-5)+ assert not normalized[1].any()+ assert not normalized[2].any()