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.

feat(image-map): pick eps by walking the k-distance quantiles

Lincoln Stein7a82c5fb9fa2
diff --git a/invokeai/app/services/image_index/projection.py b/invokeai/app/services/image_index/projection.py
index c1e54f61d6..049fd51827 100644
--- a/invokeai/app/services/image_index/projection.py
+++ b/invokeai/app/services/image_index/projection.py
@@ -6,10 +6,11 @@ app startup or break the app if the dependency stack is unhealthy.
Parameters follow PhotoMapAI's tuning: UMAP(n_neighbors=min(15, N-1),
n_components=2, min_dist=0.05, metric="cosine") and DBSCAN(min_samples=10)
-over the 2D coordinates. Unlike PhotoMapAI (fixed eps=0.2 plus a user-facing
-slider), eps defaults to an adaptive value: UMAP's output scale grows as the
-point count shrinks, so any fixed eps that works for a dense thousand-image
-map labels a small gallery as all noise.
+over the 2D coordinates. eps defaults to an adaptive value derived from the
+coordinates themselves — UMAP's output scale grows as the point count
+shrinks, so any fixed eps that works for a dense thousand-image map labels a
+small gallery as all noise — and the clustering-strength control lets a user
+override it per map.
"""
import hashlib
@@ -93,33 +94,131 @@ def compute_umap(embeddings: np.ndarray, seed: int = DEFAULT_UMAP_SEED) -> np.nd
# the image_map router — so it is set from measurement, not headroom.
MAX_CLUSTERED_POINTS = 300_000
-# eps is clamped to this fraction of the projection's coordinate span. UMAP's
-# output scale is data-dependent, so an absolute eps close to the span makes
-# every point a neighbor of every other (O(N^2) memory in sklearn's DBSCAN).
-MAX_EPS_SPAN_FRACTION = 0.05
-
-
-def adaptive_cluster_eps(coords: np.ndarray, min_samples: int = DEFAULT_CLUSTER_MIN_SAMPLES) -> float:
- """Median k-distance of the coordinates: each point's distance to its
- min_samples-th nearest neighbor, aggregated with the median.
-
- This is the standard DBSCAN eps heuristic: a point whose min_samples-th
- neighbor is within eps is a core point, so the median k-distance makes
- roughly half the points core points — clusters form wherever density is
- above the map's typical density, at any gallery size or UMAP scale.
+# A DERIVED eps is clamped to this fraction of the projection's coordinate
+# span (a requested one is not — see resolve_cluster_eps). UMAP's output scale
+# is data-dependent, so an eps close to the span makes every point a neighbor
+# of every other.
+#
+# 0.05 here was correct for a median k-distance, which sits low in the
+# distribution. The quantile scan deliberately climbs past the median, and at
+# 0.05 the clamp overrode the scan's answer outright on a map of a few
+# well-separated blobs. PhotoMapAI records making exactly this mistake by
+# copying the 0.05 from here. The pair budget below, not this, is what bounds
+# memory; this is only a sanity bound on an automatically chosen number, so it
+# is set where it catches absurdity and nothing else.
+MAX_EPS_SPAN_FRACTION = 0.25
+
+
+# Quantiles of the k-distance distribution, ascending, that the scan walks.
+# Coarse on purpose: each step costs a DBSCAN fit, and near the knee the
+# resulting eps values are within a few percent of each other anyway.
+CANDIDATE_QUANTILES: tuple[int, ...] = (40, 50, 60, 70, 80, 90)
+
+# A cluster holding more than this share of the gallery is a blob, not a
+# cluster: it is what the map looks like just before every point merges into
+# one component. Ported from PhotoMapAI, where this was measured against real
+# albums and the last candidate below it consistently landed on the value a
+# human had tuned by hand.
+MAX_TOP_CLUSTER_SHARE = 0.25
+
+
+def _k_distances(coords: np.ndarray, min_samples: int) -> Optional[np.ndarray]:
+ """Each point's distance to its min_samples-th nearest neighbor.
+
+ None when the map is too small to have one. Imported lazily because
+ sklearn's neighbors module is not free to import.
"""
n_points = coords.shape[0]
k = min(min_samples, n_points - 1)
if k < 1:
- return DEFAULT_CLUSTER_EPS
+ return None
from sklearn.neighbors import NearestNeighbors
# k + 1 neighbors because each point's nearest neighbor is itself.
distances, _ = NearestNeighbors(n_neighbors=k + 1).fit(coords).kneighbors(coords)
- eps = float(np.median(distances[:, -1]))
- # Coincident points give a zero k-distance; zero eps clusters nothing.
- return eps if eps > 0 else DEFAULT_CLUSTER_EPS
+ return distances[:, -1]
+
+
+def _top_cluster_share(coords: np.ndarray, eps: float, min_samples: int) -> float:
+ """Share of the gallery held by the largest cluster at eps.
+
+ Noise is excluded, so an eps that clusters nothing scores 0 and the scan
+ keeps climbing. Returns 1.0 for a candidate whose neighborhoods would
+ exceed the pair budget: that eps is unaffordable, which for the scan's
+ purposes is the same answer as "it has collapsed the map".
+ """
+ from sklearn.cluster import DBSCAN
+ from sklearn.neighbors import KDTree
+
+ if coords.shape[0] > 1:
+ pairs = int(KDTree(coords).query_radius(coords, r=eps, count_only=True).sum())
+ if pairs > MAX_NEIGHBOR_PAIRS:
+ return 1.0
+
+ labels = DBSCAN(eps=eps, min_samples=min_samples).fit(coords).labels_
+ clustered = labels[labels >= 0]
+ if clustered.size == 0:
+ return 0.0
+ return float(np.bincount(clustered).max()) / float(labels.size)
+
+
+def adaptive_cluster_eps(coords: np.ndarray, min_samples: int = DEFAULT_CLUSTER_MIN_SAMPLES) -> float:
+ """The loosest eps that has not yet collapsed the map into one cluster.
+
+ Candidates are quantiles of the k-distance distribution, so they are
+ expressed in the units of THESE coordinates — which is what makes the
+ result independent of gallery size and of UMAP's arbitrary output scale.
+ The scan walks them upward and keeps the last one whose largest cluster
+ stays under MAX_TOP_CLUSTER_SHARE.
+
+ This replaces taking the median outright. The median makes about half the
+ points core points by construction, which measures at 29-35% noise on a
+ large gallery — far more unclustered than a hand-tuned eps gives, and the
+ reason a 170k-image map read as mostly noise even once it was clustering
+ at all. Walking up the quantiles instead stops right before one cluster
+ swallows the map. Ported from PhotoMapAI, which reports the rule
+ reproducing hand-tuned values on real albums (0.119 against a hand-set
+ 0.12 on 38k images; 0.051 against 0.05 on 86k).
+
+ If even the smallest candidate is over the share there is no structure to
+ separate, and the smallest is returned: going lower only turns the blob
+ into noise without revealing anything.
+ """
+ distances = _k_distances(coords, min_samples)
+ if distances is None:
+ return DEFAULT_CLUSTER_EPS
+
+ # Coincident points give a zero k-distance, and eps=0 clusters nothing.
+ candidates = [eps for eps in (float(np.percentile(distances, q)) for q in CANDIDATE_QUANTILES) if eps > 0]
+ if not candidates:
+ return DEFAULT_CLUSTER_EPS
+
+ # Raising eps only adds neighbors and core points, so every cluster at one
+ # eps is contained in a cluster at any larger eps: the top share is
+ # monotone non-decreasing, and the acceptable candidates are a prefix.
+ # That makes the boundary searchable rather than walkable, which matters
+ # because each probe is a full DBSCAN fit — 1.1s per probe on a
+ # 170k-point map, so a six-candidate walk is most of ten seconds.
+ top = len(candidates) - 1
+
+ # The loosest candidate first: on a map with real structure nothing
+ # blobs, and that answers the whole scan in a single fit.
+ if _top_cluster_share(coords, candidates[top], min_samples) <= MAX_TOP_CLUSTER_SHARE:
+ return candidates[top]
+
+ lo, hi, best = 0, top - 1, -1
+ while lo <= hi:
+ mid = (lo + hi) // 2
+ if _top_cluster_share(coords, candidates[mid], min_samples) <= MAX_TOP_CLUSTER_SHARE:
+ best = mid
+ lo = mid + 1
+ else:
+ hi = mid - 1
+
+ # Nothing passed: there is no structure to separate, and going tighter
+ # only turns the blob into noise without revealing anything.
+ return candidates[best] if best >= 0 else candidates[0]
# sklearn's DBSCAN materializes every point's radius neighborhood as int64
diff --git a/tests/app/services/image_index/test_projection.py b/tests/app/services/image_index/test_projection.py
index 74537aa1c8..da0ca95e0a 100644
--- a/tests/app/services/image_index/test_projection.py
+++ b/tests/app/services/image_index/test_projection.py
@@ -6,9 +6,12 @@ import numpy as np
from invokeai.app.services.image_index.image_index_common import IndexedItem
from invokeai.app.services.image_index.projection import (
+ CANDIDATE_QUANTILES,
DEFAULT_CLUSTER_EPS,
+ DEFAULT_CLUSTER_MIN_SAMPLES,
MAX_CLUSTERED_POINTS,
MAX_EPS_SPAN_FRACTION,
+ MAX_TOP_CLUSTER_SHARE,
adaptive_cluster_eps,
cluster_with_diagnostics,
compute_clusters,
@@ -123,7 +126,7 @@ def test_eps_shrinks_to_fit_neighbor_pair_budget(monkeypatch) -> None:
coords = np.vstack([dense, sparse]).astype(np.float32)
unbudgeted = resolve_cluster_eps(coords).resolved_eps
- monkeypatch.setattr(projection, "MAX_NEIGHBOR_PAIRS", 5_000)
+ monkeypatch.setattr(projection, "MAX_NEIGHBOR_PAIRS", 2_000)
budgeted = resolve_cluster_eps(coords).resolved_eps
assert budgeted < unbudgeted
@@ -141,6 +144,99 @@ def test_resolve_cluster_eps_is_idempotent() -> None:
assert resolve_cluster_eps(coords, eps=resolved).resolved_eps == resolved
+def _linear_quantile_scan(coords: np.ndarray, min_samples: int) -> float:
+ """The reference implementation: walk the candidates, keep the last one
+ under the share. `adaptive_cluster_eps` binary-searches the same boundary."""
+ from invokeai.app.services.image_index import projection
+
+ distances = projection._k_distances(coords, min_samples)
+ assert distances is not None
+ candidates = [eps for eps in (float(np.percentile(distances, q)) for q in CANDIDATE_QUANTILES) if eps > 0]
+ best = candidates[0]
+ for eps in candidates:
+ if projection._top_cluster_share(coords, eps, min_samples) > MAX_TOP_CLUSTER_SHARE:
+ break
+ best = eps
+
+ return best
+
+
+def test_the_quantile_scan_leaves_most_of_a_structured_map_clustered() -> None:
+ """The reason the scan exists: a median k-distance leaves ~30% noise.
+
+ Roughly half the points are non-core under the median by construction, so
+ a map with real structure still reads as mostly unclustered. The scan
+ climbs past the median instead, stopping before one cluster swallows it.
+ """
+ rng = np.random.default_rng(1)
+ centers = rng.uniform(-40.0, 40.0, size=(60, 2))
+ coords = np.concatenate([c + rng.normal(scale=0.35, size=(250, 2)) for c in centers]).astype(np.float32)
+
+ _, scanned = cluster_with_diagnostics(coords)
+ median_eps = float(np.percentile(_k_distances_for(coords, DEFAULT_CLUSTER_MIN_SAMPLES), 50))
+ _, at_median = cluster_with_diagnostics(coords, eps=median_eps)
+
+ assert scanned.unclustered / scanned.n_points < 0.10
+ assert at_median.unclustered > scanned.unclustered * 3, "the median is the baseline the scan improves on"
+ # And it stops short of a blob: no cluster owns the map.
+ assert scanned.largest_cluster / scanned.n_points <= MAX_TOP_CLUSTER_SHARE
+
+
+def test_the_quantile_scan_refuses_to_let_one_cluster_swallow_the_map() -> None:
+ # Two dense blobs with nothing between them: past a point every candidate
+ # merges them, and the scan has to stop before that.
+ rng = np.random.default_rng(2)
+ coords = np.concatenate([rng.normal(scale=0.4, size=(400, 2)) + c for c in ([0.0, 0.0], [1.6, 0.0])]).astype(
+ np.float32
+ )
+
+ _, diagnostics = cluster_with_diagnostics(coords)
+
+ assert diagnostics.cluster_count >= 2, "the two blobs must not be merged into one"
+ assert diagnostics.largest_cluster / diagnostics.n_points <= MAX_TOP_CLUSTER_SHARE + 0.25
+
+
+def test_the_binary_search_finds_the_same_eps_as_walking_the_candidates() -> None:
+ """The search is only valid because the top share is monotone in eps.
+
+ If it ever is not — or the search is written wrong — it silently returns a
+ different strength than the rule describes, on some maps only.
+ """
+ rng = np.random.default_rng(7)
+ fixtures = [
+ np.concatenate([rng.uniform(-40, 40, size=(1, 2)) + rng.normal(scale=0.35, size=(500, 2)) for _ in range(8)]),
+ np.concatenate([rng.uniform(-40, 40, size=(1, 2)) + rng.normal(scale=0.5, size=(250, 2)) for _ in range(3)]),
+ rng.uniform(-10.0, 10.0, size=(600, 2)),
+ np.vstack([rng.normal(scale=1.0, size=(700, 2)), rng.uniform(-40, 40, size=(300, 2))]),
+ np.concatenate([rng.normal(scale=0.1, size=(200, 2)) + o for o in ([0, 0], [5, 5])]),
+ ]
+ # Five separated blobs plus one pair whose gap decides how many candidates
+ # bridge it — which walks the accepted boundary across the whole candidate
+ # list. Without these the search's bounds are never exercised near the top,
+ # and an off-by-one in them passes.
+ fixtures += [_five_blobs_and_a_pair(gap) for gap in (1.0, 1.2, 1.4, 1.6, 1.8)]
+
+ for index, fixture in enumerate(fixtures):
+ coords = fixture.astype(np.float32)
+ assert adaptive_cluster_eps(coords) == _linear_quantile_scan(coords, DEFAULT_CLUSTER_MIN_SAMPLES), index
+
+
+def _five_blobs_and_a_pair(gap: float) -> np.ndarray:
+ rng = np.random.default_rng(5)
+ centers = [(0.0, 0.0), (12.0, 0.0), (0.0, 12.0), (12.0, 12.0), (24.0, 6.0), (24.0 + gap, 6.0)]
+
+ return np.concatenate([rng.normal(scale=0.3, size=(200, 2)) + c for c in centers]).astype(np.float32)
+
+
+def _k_distances_for(coords: np.ndarray, min_samples: int) -> np.ndarray:
+ from invokeai.app.services.image_index import projection
+
+ distances = projection._k_distances(coords, min_samples)
+ assert distances is not None
+
+ return distances
+
+
def test_a_derived_eps_is_clamped_to_the_span_fraction() -> None:
# 20 scattered points: the median k-distance is half the map wide, which
# says there is no density structure to find. Clustering at that radius
@@ -305,15 +401,15 @@ def test_diagnostics_report_each_link_of_the_eps_chain() -> None:
def test_diagnostics_separate_the_span_clamp_from_the_eps_floor() -> None:
"""Both can produce a too-tight eps, and the log has to say which one did."""
- # A 0.07-wide map: the clamp takes the derived eps to 0.0037, and the 0.01
+ # A 0.02-wide map: the clamp takes the derived eps to 0.0049, and the 0.01
# floor then lifts it back. One number could not distinguish the two.
rng = np.random.default_rng(4)
- rng.uniform(0.0, 1.0, size=(20, 2))
- coords = rng.uniform(0.0, 0.08, size=(30, 2)).astype(np.float32)
+ coords = rng.uniform(0.0, 0.02, size=(30, 2)).astype(np.float32)
resolution = resolve_cluster_eps(coords, None, 10)
- assert resolution.adaptive_eps is not None and resolution.adaptive_eps > 0.01
- assert resolution.span_clamped_eps < 0.01, "the clamp took it below the floor"
+ assert resolution.adaptive_eps is not None
+ assert resolution.span_clamped_eps < resolution.adaptive_eps, "the clamp bound the derived value"
+ assert resolution.span_clamped_eps < 0.01, "and took it below the floor"
assert resolution.floored_eps == 0.01, "and the floor put it back"
assert "floored_eps=0.01" in cluster_with_diagnostics(coords, min_samples=10)[1].signature()