gist-select 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
gist/__init__.py ADDED
@@ -0,0 +1,20 @@
1
+ from .algorithm import GISTResult, gist
2
+ from .distances import (
3
+ CallableDistance,
4
+ CosineDistance,
5
+ DistanceMetric,
6
+ EuclideanDistance,
7
+ )
8
+ from .objectives import CoverageFunction, LinearUtility, SubmodularFunction
9
+
10
+ __all__ = [
11
+ "gist",
12
+ "GISTResult",
13
+ "SubmodularFunction",
14
+ "LinearUtility",
15
+ "CoverageFunction",
16
+ "DistanceMetric",
17
+ "EuclideanDistance",
18
+ "CosineDistance",
19
+ "CallableDistance",
20
+ ]
gist/algorithm.py ADDED
@@ -0,0 +1,267 @@
1
+ from __future__ import annotations
2
+
3
+ import heapq
4
+ from dataclasses import dataclass
5
+
6
+ import numpy as np
7
+ import numpy.typing as npt
8
+
9
+ from .distances import DistanceMetric, approximate_diameter
10
+ from .objectives import SubmodularFunction
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class GISTResult:
15
+ """Result returned by :func:`gist`."""
16
+
17
+ indices: npt.NDArray[np.intp]
18
+ """Indices of the selected points."""
19
+ objective_value: float
20
+ """``f(S) = g(S) + lambda * div(S)``."""
21
+ utility_value: float
22
+ """``g(S)``."""
23
+ diversity: float
24
+ """``div(S)`` — the minimum pairwise distance in the selected set."""
25
+
26
+
27
+ # ---------------------------------------------------------------------------
28
+ # GreedyIndependentSet with CELF
29
+ # ---------------------------------------------------------------------------
30
+
31
+ def _greedy_independent_set(
32
+ points: npt.NDArray[np.floating],
33
+ utility: SubmodularFunction,
34
+ metric: DistanceMetric,
35
+ d: float,
36
+ k: int,
37
+ ) -> tuple[list[int], float]:
38
+ """GreedyIndependentSet from Algorithm 1, accelerated with CELF.
39
+
40
+ Returns ``(selected_indices, min_pairwise_distance)``.
41
+ ``min_pairwise_distance`` is ``inf`` when ``|selected| <= 1``.
42
+ """
43
+ n = len(points)
44
+ selected: list[int] = []
45
+ min_pairwise = np.inf
46
+
47
+ # Active set — boolean for O(1) lookup, index array for distance ops.
48
+ is_active = np.ones(n, dtype=bool)
49
+ active_indices = np.arange(n, dtype=np.intp)
50
+
51
+ # CELF heap: entries are (-gain, eval_iteration, index).
52
+ # Python heapq is a min-heap, so we negate gains for max-heap behaviour.
53
+ all_indices = np.arange(n, dtype=np.intp)
54
+ initial_gains = utility.marginal_gains([], all_indices)
55
+ # Use a tiebreaker counter to ensure stable ordering when gains are equal.
56
+ counter = 0
57
+ heap: list[tuple[float, int, int, int]] = []
58
+ for idx in range(n):
59
+ heap.append((-float(initial_gains[idx]), counter, -1, idx))
60
+ counter += 1
61
+ heapq.heapify(heap)
62
+
63
+ for iteration in range(k):
64
+ found = False
65
+ while heap:
66
+ neg_gain, _cnt, eval_iter, idx = heapq.heappop(heap)
67
+
68
+ # Lazy deletion: skip eliminated points.
69
+ if not is_active[idx]:
70
+ continue
71
+
72
+ # If gain was evaluated in this iteration, it is current — select.
73
+ if eval_iter == iteration:
74
+ # --- SELECT idx ---
75
+ selected.append(idx)
76
+ is_active[idx] = False
77
+
78
+ # Track min pairwise distance incrementally.
79
+ if len(selected) >= 2:
80
+ prev = np.array(selected[:-1], dtype=np.intp)
81
+ dists_to_prev = metric.from_point(points, idx, prev)
82
+ min_pairwise = min(min_pairwise, float(dists_to_prev.min()))
83
+
84
+ # Eliminate points within distance d.
85
+ if d > 0:
86
+ active_indices = np.where(is_active)[0]
87
+ if len(active_indices) > 0:
88
+ dists = metric.from_point(points, idx, active_indices)
89
+ to_elim = active_indices[dists < d]
90
+ is_active[to_elim] = False
91
+ active_indices = np.where(is_active)[0]
92
+
93
+ found = True
94
+ break
95
+
96
+ # Gain is stale — re-evaluate and push back.
97
+ new_gain = utility.marginal_gains(selected, np.array([idx], dtype=np.intp))
98
+ heapq.heappush(heap, (-float(new_gain[0]), counter, iteration, idx))
99
+ counter += 1
100
+
101
+ if not found:
102
+ break # No more candidates.
103
+
104
+ return selected, float(min_pairwise)
105
+
106
+
107
+ # ---------------------------------------------------------------------------
108
+ # Threshold construction
109
+ # ---------------------------------------------------------------------------
110
+
111
+ def _build_thresholds(d_max: float, eps: float) -> npt.NDArray[np.floating]:
112
+ """D = {(1+eps)^i * eps*d_max/2 : (1+eps)^i <= 2/eps, i >= 0}."""
113
+ base = eps * d_max / 2.0
114
+ limit = 2.0 / eps
115
+ thresholds: list[float] = []
116
+ mult = 1.0
117
+ while mult <= limit:
118
+ thresholds.append(base * mult)
119
+ mult *= 1.0 + eps
120
+ return np.array(thresholds, dtype=np.float64)
121
+
122
+
123
+ # ---------------------------------------------------------------------------
124
+ # Main GIST function
125
+ # ---------------------------------------------------------------------------
126
+
127
+ def gist(
128
+ points: npt.NDArray[np.floating],
129
+ utility: SubmodularFunction,
130
+ distance: DistanceMetric,
131
+ k: int,
132
+ lam: float = 1.0,
133
+ eps: float = 0.05,
134
+ n_jobs: int = 1,
135
+ seed: int | None = None,
136
+ diameter: tuple[float, int, int] | None = None,
137
+ ) -> GISTResult:
138
+ """GIST algorithm for max-min diversification with submodular utility.
139
+
140
+ Maximises ``f(S) = g(S) + lam * div(S)`` subject to ``|S| <= k``,
141
+ where ``g`` is a monotone submodular function and ``div(S)`` is the
142
+ minimum pairwise distance in *S*.
143
+
144
+ Parameters
145
+ ----------
146
+ points : ndarray, shape ``(n, d)``
147
+ Data points in a *d*-dimensional space.
148
+ utility : SubmodularFunction
149
+ Monotone submodular utility function ``g``.
150
+ distance : DistanceMetric
151
+ Distance metric for the point set.
152
+ k : int
153
+ Cardinality constraint (maximum selected points).
154
+ lam : float
155
+ Diversity strength ``lambda >= 0``.
156
+ eps : float
157
+ Approximation parameter ``epsilon > 0``. Controls the number of
158
+ distance thresholds (~76 for ``eps=0.05``).
159
+ n_jobs : int
160
+ Number of threads for the threshold sweep. Requires *joblib*
161
+ when ``n_jobs != 1``.
162
+ seed : int, optional
163
+ Random seed for reproducibility.
164
+ diameter : tuple, optional
165
+ Pre-computed ``(d_max, idx_u, idx_v)``. If ``None``, the
166
+ diameter is approximated via a multi-start double-scan.
167
+
168
+ Returns
169
+ -------
170
+ GISTResult
171
+ """
172
+ # --- Input validation (system boundary) --------------------------------
173
+ points = np.asarray(points)
174
+ if points.ndim != 2:
175
+ raise ValueError(f"points must be 2-D, got {points.ndim}-D")
176
+
177
+ n = len(points)
178
+ if n == 0 or k < 1:
179
+ return GISTResult(np.array([], dtype=np.intp), 0.0, 0.0, 0.0)
180
+ k = min(k, n)
181
+ if lam < 0:
182
+ raise ValueError(f"lam must be >= 0, got {lam}")
183
+ if eps <= 0:
184
+ raise ValueError(f"eps must be > 0, got {eps}")
185
+
186
+ rng = np.random.default_rng(seed)
187
+
188
+ # --- Preprocess --------------------------------------------------------
189
+ points = distance.prepare(points)
190
+
191
+ # --- Step 1: Classic greedy (d = 0) ------------------------------------
192
+ best_sel, best_min_pw = _greedy_independent_set(points, utility, distance, 0.0, k)
193
+
194
+ # --- Step 2: Approximate diameter --------------------------------------
195
+ if diameter is None:
196
+ d_max, u, v = approximate_diameter(points, distance, rng)
197
+ else:
198
+ d_max, u, v = diameter
199
+
200
+ # Helper to compute div(S) from tracked min pairwise distance.
201
+ def _diversity(sel: list[int], min_pw: float) -> float:
202
+ if len(sel) >= 2:
203
+ return min_pw
204
+ return d_max # Paper convention: div(S) = diameter when |S| <= 1.
205
+
206
+ def _objective(sel: list[int], min_pw: float) -> tuple[float, float, float]:
207
+ g = utility.value(sel)
208
+ div = _diversity(sel, min_pw)
209
+ return g + lam * div, g, div
210
+
211
+ best_obj, best_g, best_div = _objective(best_sel, best_min_pw)
212
+
213
+ # --- Step 3: Diametrical pair ------------------------------------------
214
+ if k >= 2 and d_max > 0:
215
+ pair = [u, v]
216
+ pair_obj, pair_g, pair_div = _objective(pair, d_max)
217
+ if pair_obj > best_obj:
218
+ best_sel, best_obj, best_g, best_div = pair, pair_obj, pair_g, pair_div
219
+
220
+ # --- Step 4: Threshold sweep -------------------------------------------
221
+ if d_max <= 0:
222
+ # Degenerate: all points coincide.
223
+ return GISTResult(np.array(best_sel, dtype=np.intp), best_obj, best_g, best_div)
224
+
225
+ thresholds = _build_thresholds(d_max, eps)
226
+
227
+ def _run_threshold(d_val: float) -> tuple[list[int], float, float, float] | None:
228
+ sel, min_pw = _greedy_independent_set(points, utility, distance, d_val, k)
229
+ if len(sel) <= 1:
230
+ return None # Dominated by diametrical pair.
231
+ obj, g, div = _objective(sel, min_pw)
232
+ return sel, obj, g, div
233
+
234
+ if n_jobs == 1:
235
+ # Sequential with early stopping.
236
+ for d_val in thresholds:
237
+ result = _run_threshold(d_val)
238
+ if result is None:
239
+ break # Larger thresholds only make it harder.
240
+ sel, obj, g, div = result
241
+ if obj >= best_obj:
242
+ best_sel, best_obj, best_g, best_div = sel, obj, g, div
243
+ else:
244
+ try:
245
+ from joblib import Parallel, delayed
246
+ except ImportError:
247
+ raise ImportError(
248
+ "joblib is required for n_jobs != 1. "
249
+ "Install with: pip install 'gist-select[parallel]'"
250
+ ) from None
251
+
252
+ results = Parallel(n_jobs=n_jobs, prefer="threads")(
253
+ delayed(_run_threshold)(d_val) for d_val in thresholds
254
+ )
255
+ for result in results:
256
+ if result is None:
257
+ continue
258
+ sel, obj, g, div = result
259
+ if obj >= best_obj:
260
+ best_sel, best_obj, best_g, best_div = sel, obj, g, div
261
+
262
+ return GISTResult(
263
+ indices=np.array(best_sel, dtype=np.intp),
264
+ objective_value=best_obj,
265
+ utility_value=best_g,
266
+ diversity=best_div,
267
+ )
gist/distances.py ADDED
@@ -0,0 +1,143 @@
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+
5
+ import numpy as np
6
+ import numpy.typing as npt
7
+
8
+
9
+ class DistanceMetric(ABC):
10
+ """Abstract base class for distance metrics."""
11
+
12
+ def prepare(self, points: npt.NDArray[np.floating]) -> npt.NDArray[np.floating]:
13
+ """Optional preprocessing called once before the algorithm runs.
14
+
15
+ Can store precomputed data on ``self`` and return (possibly
16
+ transformed) points. The default implementation is the identity.
17
+ """
18
+ return points
19
+
20
+ @abstractmethod
21
+ def from_point(
22
+ self,
23
+ points: npt.NDArray[np.floating],
24
+ source: int,
25
+ targets: npt.NDArray[np.intp],
26
+ ) -> npt.NDArray[np.floating]:
27
+ """Distances from ``points[source]`` to ``points[targets]``.
28
+
29
+ Returns a 1-D array with the same length as *targets*.
30
+ """
31
+ ...
32
+
33
+
34
+ class EuclideanDistance(DistanceMetric):
35
+ """Euclidean distance using the norm identity trick.
36
+
37
+ ``||a - b||^2 = ||a||^2 + ||b||^2 - 2 * (a . b)``
38
+
39
+ ``prepare`` precomputes squared norms so the hot path is a single
40
+ BLAS GEMV (dot product) plus cheap vector arithmetic.
41
+ """
42
+
43
+ _norms_sq: npt.NDArray[np.floating]
44
+
45
+ def prepare(self, points: npt.NDArray[np.floating]) -> npt.NDArray[np.floating]:
46
+ self._norms_sq = np.einsum("ij,ij->i", points, points)
47
+ return points
48
+
49
+ def from_point(
50
+ self,
51
+ points: npt.NDArray[np.floating],
52
+ source: int,
53
+ targets: npt.NDArray[np.intp],
54
+ ) -> npt.NDArray[np.floating]:
55
+ dots = points[targets] @ points[source]
56
+ sq = self._norms_sq[targets] + self._norms_sq[source] - 2.0 * dots
57
+ np.maximum(sq, 0.0, out=sq)
58
+ return np.sqrt(sq)
59
+
60
+
61
+ class CosineDistance(DistanceMetric):
62
+ """Cosine distance: ``1 - cos(a, b)``.
63
+
64
+ ``prepare`` normalises the points to unit length so the hot path
65
+ reduces to ``1 - dot(a, b)``.
66
+ """
67
+
68
+ def prepare(self, points: npt.NDArray[np.floating]) -> npt.NDArray[np.floating]:
69
+ norms = np.linalg.norm(points, axis=1, keepdims=True)
70
+ np.maximum(norms, 1e-10, out=norms)
71
+ return (points / norms).astype(points.dtype)
72
+
73
+ def from_point(
74
+ self,
75
+ points: npt.NDArray[np.floating],
76
+ source: int,
77
+ targets: npt.NDArray[np.intp],
78
+ ) -> npt.NDArray[np.floating]:
79
+ dots = points[targets] @ points[source]
80
+ return 1.0 - dots
81
+
82
+
83
+ class CallableDistance(DistanceMetric):
84
+ """Wraps a user-provided vectorised distance function.
85
+
86
+ Parameters
87
+ ----------
88
+ fn : callable
89
+ ``fn(source_vector, target_matrix) -> distances`` where
90
+ *source_vector* has shape ``(d,)`` and *target_matrix* has shape
91
+ ``(m, d)``. Must return a 1-D array of length *m*.
92
+ """
93
+
94
+ def __init__(
95
+ self,
96
+ fn: "callable[[npt.NDArray, npt.NDArray], npt.NDArray]",
97
+ ) -> None:
98
+ self._fn = fn
99
+
100
+ def from_point(
101
+ self,
102
+ points: npt.NDArray[np.floating],
103
+ source: int,
104
+ targets: npt.NDArray[np.intp],
105
+ ) -> npt.NDArray[np.floating]:
106
+ return self._fn(points[source], points[targets])
107
+
108
+
109
+ def approximate_diameter(
110
+ points: npt.NDArray[np.floating],
111
+ metric: DistanceMetric,
112
+ rng: np.random.Generator,
113
+ n_starts: int = 5,
114
+ ) -> tuple[float, int, int]:
115
+ """Multi-start double-scan heuristic for the approximate diameter.
116
+
117
+ Runs *n_starts* independent double-scans from random starting points
118
+ and returns the pair with the largest distance found. Cost is
119
+ ``2 * n_starts`` one-to-all distance computations.
120
+ """
121
+ n = len(points)
122
+ all_indices = np.arange(n, dtype=np.intp)
123
+
124
+ best_dist = -1.0
125
+ best_u = 0
126
+ best_v = 0
127
+
128
+ for _ in range(n_starts):
129
+ start = int(rng.integers(n))
130
+
131
+ dists = metric.from_point(points, start, all_indices)
132
+ u = int(np.argmax(dists))
133
+
134
+ dists = metric.from_point(points, u, all_indices)
135
+ v = int(np.argmax(dists))
136
+
137
+ d = float(dists[v])
138
+ if d > best_dist:
139
+ best_dist = d
140
+ best_u = u
141
+ best_v = v
142
+
143
+ return best_dist, best_u, best_v
gist/objectives.py ADDED
@@ -0,0 +1,113 @@
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+
5
+ import numpy as np
6
+ import numpy.typing as npt
7
+
8
+
9
+ class SubmodularFunction(ABC):
10
+ """Abstract base class for monotone submodular utility functions."""
11
+
12
+ @abstractmethod
13
+ def marginal_gains(
14
+ self,
15
+ selected: list[int],
16
+ candidates: npt.NDArray[np.intp],
17
+ ) -> npt.NDArray[np.floating]:
18
+ """Marginal gain ``g(v | S)`` for each *v* in *candidates*.
19
+
20
+ Parameters
21
+ ----------
22
+ selected : list[int]
23
+ Indices currently in the selected set *S*, in selection order.
24
+ candidates : ndarray of int
25
+ Indices of candidate points to evaluate.
26
+
27
+ Returns
28
+ -------
29
+ ndarray
30
+ 1-D float array of marginal gains, same length as *candidates*.
31
+ """
32
+ ...
33
+
34
+ @abstractmethod
35
+ def value(self, selected: list[int]) -> float:
36
+ """Evaluate ``g(S)`` for the given set of indices."""
37
+ ...
38
+
39
+
40
+ class LinearUtility(SubmodularFunction):
41
+ """Additive (linear) utility: ``g(S) = sum_{v in S} weights[v]``.
42
+
43
+ Marginal gains are simply the individual weights and do not depend
44
+ on *S*. This is the special case for which GIST achieves a tight
45
+ ``2/3``-approximation guarantee.
46
+ """
47
+
48
+ def __init__(self, weights: npt.NDArray[np.floating]) -> None:
49
+ self._weights = np.asarray(weights, dtype=np.float64)
50
+
51
+ def marginal_gains(
52
+ self,
53
+ selected: list[int],
54
+ candidates: npt.NDArray[np.intp],
55
+ ) -> npt.NDArray[np.floating]:
56
+ return self._weights[candidates]
57
+
58
+ def value(self, selected: list[int]) -> float:
59
+ if not selected:
60
+ return 0.0
61
+ return float(np.sum(self._weights[selected]))
62
+
63
+
64
+ class CoverageFunction(SubmodularFunction):
65
+ """Set-coverage utility: ``g(S) = |union_{i in S} cover(i)|``.
66
+
67
+ Optionally weighted: ``g(S) = sum of element_weights[j]`` for all
68
+ elements *j* covered by at least one point in *S*.
69
+
70
+ Parameters
71
+ ----------
72
+ coverage_matrix : scipy.sparse.csr_matrix
73
+ Binary ``(n_points, n_elements)`` sparse matrix where entry
74
+ ``(i, j) = 1`` means point *i* covers element *j*.
75
+ element_weights : ndarray, optional
76
+ Per-element weights. If ``None``, all elements have weight 1.
77
+ """
78
+
79
+ def __init__(
80
+ self,
81
+ coverage_matrix: "scipy.sparse.csr_matrix",
82
+ element_weights: npt.NDArray[np.floating] | None = None,
83
+ ) -> None:
84
+ self._cov = coverage_matrix
85
+ self._n_elements = coverage_matrix.shape[1]
86
+ self._ew = element_weights
87
+
88
+ def _covered_mask(self, selected: list[int]) -> npt.NDArray[np.bool_]:
89
+ covered = np.zeros(self._n_elements, dtype=bool)
90
+ for idx in selected:
91
+ covered[self._cov[idx].indices] = True
92
+ return covered
93
+
94
+ def marginal_gains(
95
+ self,
96
+ selected: list[int],
97
+ candidates: npt.NDArray[np.intp],
98
+ ) -> npt.NDArray[np.floating]:
99
+ covered = self._covered_mask(selected)
100
+ gains = np.empty(len(candidates), dtype=np.float64)
101
+ for i, c in enumerate(candidates):
102
+ new = self._cov[c].indices[~covered[self._cov[c].indices]]
103
+ if self._ew is None:
104
+ gains[i] = len(new)
105
+ else:
106
+ gains[i] = float(self._ew[new].sum())
107
+ return gains
108
+
109
+ def value(self, selected: list[int]) -> float:
110
+ covered = self._covered_mask(selected)
111
+ if self._ew is None:
112
+ return float(covered.sum())
113
+ return float(self._ew[covered].sum())
gist/py.typed ADDED
File without changes
@@ -0,0 +1,393 @@
1
+ Metadata-Version: 2.4
2
+ Name: gist-select
3
+ Version: 0.1.0
4
+ Summary: GIST: Greedy Independent Set Thresholding for Max-Min Diversification with Submodular Utility
5
+ Author-email: Kenny Claka <hello@kennyigbechi.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/kclaka/gist-select
8
+ Project-URL: Repository, https://github.com/kclaka/gist-select
9
+ Project-URL: Issues, https://github.com/kclaka/gist-select/issues
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Scientific/Engineering
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: numpy>=1.24
23
+ Requires-Dist: scipy>=1.10
24
+ Provides-Extra: parallel
25
+ Requires-Dist: joblib>=1.3; extra == "parallel"
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest>=7.0; extra == "dev"
28
+ Requires-Dist: joblib>=1.3; extra == "dev"
29
+ Dynamic: license-file
30
+
31
+ # gist-select
32
+
33
+ **Greedy Independent Set Thresholding for Max-Min Diversification with Submodular Utility**
34
+
35
+ A production-grade Python implementation of the GIST algorithm from [Fahrbach et al. (NeurIPS 2025)](https://arxiv.org/abs/2405.18754). Select subsets that are both **high-quality** and **diverse** — with provable approximation guarantees.
36
+
37
+ ---
38
+
39
+ ## The Problem
40
+
41
+ You have a large pool of items (data points, images, documents, candidates) and need to select *k* of them. You want items that are **individually valuable** *and* **collectively diverse** — no redundancy, maximum coverage.
42
+
43
+ GIST solves this by maximizing:
44
+
45
+ ```
46
+ f(S) = g(S) + λ · div(S)
47
+ ```
48
+
49
+ | Term | Meaning |
50
+ |------|---------|
51
+ | `g(S)` | Monotone submodular utility — how valuable the selected set is |
52
+ | `div(S)` | Max-min diversity — the minimum pairwise distance in the set |
53
+ | `λ` | Trade-off knob between utility and diversity |
54
+
55
+ **Approximation guarantees:**
56
+ - General submodular utility: **1/2 - ε**
57
+ - Linear utility: **2/3 - ε** *(tight — matches the NP-hardness lower bound)*
58
+
59
+ ---
60
+
61
+ ## Features
62
+
63
+ - **Provably good** — constant-factor approximation guarantees from the paper
64
+ - **Fast at scale** — tested up to 2M points with high-dimensional embeddings
65
+ - **CELF acceleration** — lazy greedy evaluation reduces oracle calls by orders of magnitude
66
+ - **Optimised numerics** — BLAS-backed distance computation, precomputed norms, no large temporaries
67
+ - **Flexible metrics** — Euclidean, cosine, or bring your own distance function
68
+ - **Flexible utilities** — linear weights, set coverage, or bring your own submodular function
69
+ - **Parallel threshold sweep** — optional multi-threaded execution via joblib
70
+ - **Deterministic** — seed parameter for full reproducibility
71
+
72
+ ---
73
+
74
+ ## Installation
75
+
76
+ ```bash
77
+ pip install gist-select
78
+ ```
79
+
80
+ With optional parallel support:
81
+
82
+ ```bash
83
+ pip install "gist-select[parallel]"
84
+ ```
85
+
86
+ **Requirements:** Python ≥ 3.10, NumPy ≥ 1.24, SciPy ≥ 1.10
87
+
88
+ ---
89
+
90
+ ## Quick Start
91
+
92
+ ```python
93
+ import numpy as np
94
+ from gist import gist, LinearUtility, EuclideanDistance
95
+
96
+ # 10,000 points in 64 dimensions
97
+ rng = np.random.default_rng(42)
98
+ points = rng.standard_normal((10_000, 64)).astype(np.float32)
99
+ weights = rng.random(10_000)
100
+
101
+ # Select the 50 best-and-diverse points
102
+ result = gist(
103
+ points=points,
104
+ utility=LinearUtility(weights),
105
+ distance=EuclideanDistance(),
106
+ k=50,
107
+ lam=1.0,
108
+ seed=42,
109
+ )
110
+
111
+ print(f"Selected {len(result.indices)} points")
112
+ print(f"Objective: {result.objective_value:.4f}")
113
+ print(f"Utility: {result.utility_value:.4f}")
114
+ print(f"Diversity: {result.diversity:.4f}")
115
+ ```
116
+
117
+ ---
118
+
119
+ ## API Reference
120
+
121
+ ### `gist()`
122
+
123
+ ```python
124
+ gist(
125
+ points, # np.ndarray (n, d) — your data
126
+ utility, # SubmodularFunction — how to score subsets
127
+ distance, # DistanceMetric — how to measure spread
128
+ k, # int — how many points to select
129
+ lam=1.0, # float — diversity weight (λ ≥ 0)
130
+ eps=0.05, # float — approximation granularity (ε > 0)
131
+ n_jobs=1, # int — threads for threshold sweep
132
+ seed=None, # int — random seed for reproducibility
133
+ diameter=None, # tuple — precomputed (d_max, idx_u, idx_v)
134
+ ) -> GISTResult
135
+ ```
136
+
137
+ **Returns** a `GISTResult` with:
138
+
139
+ | Field | Type | Description |
140
+ |-------|------|-------------|
141
+ | `indices` | `np.ndarray` | Indices of selected points |
142
+ | `objective_value` | `float` | `g(S) + λ · div(S)` |
143
+ | `utility_value` | `float` | `g(S)` |
144
+ | `diversity` | `float` | `div(S)` — minimum pairwise distance |
145
+
146
+ **Parameters in detail:**
147
+
148
+ - **`lam`** — Controls the utility/diversity trade-off. Higher values favour more spread-out selections. Set to `0` for pure utility maximisation (standard greedy).
149
+ - **`eps`** — Controls the number of distance thresholds swept (~76 for `eps=0.05`, ~38 for `eps=0.1`). Smaller is more thorough but slower.
150
+ - **`n_jobs`** — Number of threads for the threshold sweep. Requires `joblib`. Uses threading backend to share memory.
151
+ - **`diameter`** — Skip the automatic diameter estimation by providing `(d_max, idx_u, idx_v)`. Useful when calling `gist()` repeatedly on the same point set.
152
+
153
+ ---
154
+
155
+ ### Distance Metrics
156
+
157
+ ```python
158
+ from gist import EuclideanDistance, CosineDistance, CallableDistance
159
+ ```
160
+
161
+ | Class | Description | Hot Path |
162
+ |-------|-------------|----------|
163
+ | `EuclideanDistance()` | L2 distance with precomputed norms | Single BLAS GEMV |
164
+ | `CosineDistance()` | `1 - cos(a, b)`, auto-normalises | Single BLAS GEMV |
165
+ | `CallableDistance(fn)` | User-provided `fn(vec, matrix) → dists` | Your function |
166
+
167
+ **Custom distance example:**
168
+
169
+ ```python
170
+ from gist import CallableDistance
171
+
172
+ def manhattan(source_vec, target_matrix):
173
+ """L1 distance — must be vectorised."""
174
+ return np.abs(target_matrix - source_vec).sum(axis=1)
175
+
176
+ distance = CallableDistance(manhattan)
177
+ ```
178
+
179
+ > **Note:** The callable signature is `fn(source: ndarray shape (d,), targets: ndarray shape (m, d)) → ndarray shape (m,)`. It *must* be vectorised — a scalar `dist(a, b)` function will not work at scale.
180
+
181
+ ---
182
+
183
+ ### Submodular Utilities
184
+
185
+ ```python
186
+ from gist import LinearUtility, CoverageFunction, SubmodularFunction
187
+ ```
188
+
189
+ #### `LinearUtility(weights)`
190
+
191
+ Additive utility: `g(S) = Σ weights[i]` for `i ∈ S`.
192
+
193
+ This is the most common case and the fastest — marginal gains are just individual weights. GIST achieves the tight **2/3-approximation** for linear utilities.
194
+
195
+ ```python
196
+ weights = np.array([0.9, 0.1, 0.8, 0.3, 0.7])
197
+ utility = LinearUtility(weights)
198
+ ```
199
+
200
+ #### `CoverageFunction(coverage_matrix, element_weights=None)`
201
+
202
+ Set-coverage utility: `g(S) = |⋃_{i ∈ S} cover(i)|`.
203
+
204
+ Each point covers a set of elements. The utility is the total number (or weighted sum) of distinct elements covered by the selected set. Classic diminishing returns.
205
+
206
+ ```python
207
+ from scipy import sparse
208
+
209
+ # 1000 points, each covering some of 500 elements
210
+ coverage_matrix = sparse.random(1000, 500, density=0.05, format="csr")
211
+ coverage_matrix.data[:] = 1 # binary
212
+
213
+ utility = CoverageFunction(coverage_matrix)
214
+ ```
215
+
216
+ #### Custom Submodular Functions
217
+
218
+ Subclass `SubmodularFunction` and implement two methods:
219
+
220
+ ```python
221
+ from gist import SubmodularFunction
222
+
223
+ class MyUtility(SubmodularFunction):
224
+ def marginal_gains(self, selected: list[int], candidates: np.ndarray) -> np.ndarray:
225
+ """Return g(v | S) for each v in candidates."""
226
+ gains = np.empty(len(candidates))
227
+ for i, v in enumerate(candidates):
228
+ gains[i] = self._compute_marginal(v, selected)
229
+ return gains
230
+
231
+ def value(self, selected: list[int]) -> float:
232
+ """Return g(S)."""
233
+ return self._compute_value(selected)
234
+ ```
235
+
236
+ > **Performance tip:** GIST uses CELF (lazy greedy) internally, so `marginal_gains` is called infrequently on small batches after the initial pass. But the initial call evaluates *all* points, so make sure it handles large `candidates` arrays efficiently.
237
+
238
+ ---
239
+
240
+ ## Examples
241
+
242
+ ### Data Sampling for Model Training
243
+
244
+ Select a representative training subset that balances uncertainty and diversity — inspired by the paper's ImageNet experiment:
245
+
246
+ ```python
247
+ import numpy as np
248
+ from gist import gist, LinearUtility, CosineDistance
249
+
250
+ # embeddings: (n, 2048) from a pretrained model
251
+ # uncertainty: (n,) margin-based uncertainty scores
252
+ embeddings = np.load("embeddings.npy")
253
+ uncertainty = np.load("uncertainty_scores.npy")
254
+
255
+ # Select 50K diverse, uncertain examples
256
+ result = gist(
257
+ points=embeddings,
258
+ utility=LinearUtility(uncertainty),
259
+ distance=CosineDistance(),
260
+ k=50_000,
261
+ lam=0.5, # balance uncertainty with diversity
262
+ eps=0.05,
263
+ n_jobs=4, # parallel threshold sweep
264
+ seed=0,
265
+ )
266
+
267
+ train_indices = result.indices
268
+ print(f"Selected {len(train_indices)} training examples")
269
+ print(f"Min pairwise cosine distance: {result.diversity:.4f}")
270
+ ```
271
+
272
+ ### Feature Selection
273
+
274
+ Select a diverse subset of features that individually have high relevance:
275
+
276
+ ```python
277
+ import numpy as np
278
+ from gist import gist, LinearUtility, EuclideanDistance
279
+
280
+ # features: (n_features, n_samples) — each row is a feature vector
281
+ features = np.load("feature_matrix.npy")
282
+ relevance_scores = np.load("relevance.npy")
283
+
284
+ result = gist(
285
+ points=features,
286
+ utility=LinearUtility(relevance_scores),
287
+ distance=EuclideanDistance(),
288
+ k=20,
289
+ lam=2.0, # strongly penalise redundant features
290
+ seed=42,
291
+ )
292
+
293
+ selected_features = result.indices
294
+ ```
295
+
296
+ ### Tuning the Diversity Trade-off
297
+
298
+ Sweep over `lam` to find the right balance for your task:
299
+
300
+ ```python
301
+ import numpy as np
302
+ from gist import gist, LinearUtility, EuclideanDistance
303
+
304
+ rng = np.random.default_rng(0)
305
+ points = rng.standard_normal((5000, 32))
306
+ weights = rng.random(5000)
307
+
308
+ for lam in [0.0, 0.5, 1.0, 2.0, 5.0]:
309
+ result = gist(
310
+ points, LinearUtility(weights), EuclideanDistance(),
311
+ k=50, lam=lam, eps=0.1, seed=0,
312
+ )
313
+ print(f"λ={lam:<4} utility={result.utility_value:.2f} "
314
+ f"diversity={result.diversity:.3f} "
315
+ f"objective={result.objective_value:.2f}")
316
+ ```
317
+
318
+ ```
319
+ λ=0.0 utility=49.47 diversity=3.041 objective=49.47
320
+ λ=0.5 utility=48.91 diversity=3.255 objective=50.54
321
+ λ=1.0 utility=48.31 diversity=3.442 objective=51.75
322
+ λ=2.0 utility=47.06 diversity=3.819 objective=54.70
323
+ λ=5.0 utility=43.98 diversity=4.607 objective=67.02
324
+ ```
325
+
326
+ ### Pure Utility Maximisation
327
+
328
+ Set `lam=0` to recover standard greedy submodular maximisation (no diversity term):
329
+
330
+ ```python
331
+ result = gist(points, utility, distance, k=100, lam=0.0)
332
+ # Equivalent to the classic (1 - 1/e)-approximation greedy
333
+ ```
334
+
335
+ ---
336
+
337
+ ## Performance
338
+
339
+ Benchmarked on Apple M-series, single-threaded, `eps=0.1`:
340
+
341
+ | Points | Dimensions | k | Time |
342
+ |--------|-----------|-----|------|
343
+ | 10K | 64 | 50 | 0.3s |
344
+ | 100K | 128 | 100 | 6s |
345
+ | 500K | 128 | 100 | ~30s |
346
+ | 2M | 128 | 100 | ~2 min |
347
+
348
+ **Scaling tips:**
349
+ - Use `float32` points — 2x memory savings and faster BLAS
350
+ - Increase `eps` (e.g., `0.1` → `0.2`) to halve the number of thresholds
351
+ - Use `n_jobs=-1` with joblib for parallel threshold sweep
352
+ - Precompute `diameter` when calling `gist()` repeatedly on the same data
353
+
354
+ ---
355
+
356
+ ## How It Works
357
+
358
+ GIST sweeps over a geometric sequence of distance thresholds. For each threshold *d*, it runs a greedy algorithm that builds a maximal independent set of the intersection graph (points within distance *d* are "neighbours") while maximising the submodular utility.
359
+
360
+ ```
361
+ GIST(V, g, k, ε):
362
+ 1. S ← GreedyIndependentSet(V, g, d=0, k) # pure utility baseline
363
+ 2. T ← diametrical pair with max distance # pure diversity baseline
364
+ 3. For each threshold d in geometric sequence:
365
+ T ← GreedyIndependentSet(V, g, d, k) # utility + diversity
366
+ Keep best f(T) = g(T) + λ · div(T)
367
+ 4. Return the best solution found
368
+ ```
369
+
370
+ The `GreedyIndependentSet` subroutine uses CELF (lazy greedy) to minimise submodular oracle calls. Points within distance *d* of a selected point are eliminated, ensuring all selected points are pairwise at distance ≥ *d*.
371
+
372
+ For the full details, see the paper: [arXiv:2405.18754](https://arxiv.org/abs/2405.18754)
373
+
374
+ ---
375
+
376
+ ## Citation
377
+
378
+ If you use this package in your research, please cite the original paper:
379
+
380
+ ```bibtex
381
+ @inproceedings{fahrbach2025gist,
382
+ title={GIST: Greedy Independent Set Thresholding for Max-Min Diversification with Submodular Utility},
383
+ author={Fahrbach, Matthew and Ramalingam, Srikumar and Zadimoghaddam, Morteza and Ahmadian, Sara and Citovsky, Gui and DeSalvo, Giulia},
384
+ booktitle={Advances in Neural Information Processing Systems (NeurIPS)},
385
+ year={2025}
386
+ }
387
+ ```
388
+
389
+ ---
390
+
391
+ ## License
392
+
393
+ MIT
@@ -0,0 +1,10 @@
1
+ gist/__init__.py,sha256=xNKlNUCW0Vxa9N02YSOSaEYp8RKed2UKJQAH3bBx1WU,437
2
+ gist/algorithm.py,sha256=ni2lP3cQb46eQknEhjZoyBe8i51UyovKyfIk5xqYVIQ,9494
3
+ gist/distances.py,sha256=BvsoO2P2hocIJMNjMZXGWcz1gmBhvI5sI3WIX-2Dkos,4144
4
+ gist/objectives.py,sha256=P7y6iSFEannu-LYW0PqSMlV11ekN6ZnTo8J3iTAeM2M,3583
5
+ gist/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ gist_select-0.1.0.dist-info/licenses/LICENSE,sha256=0w7_DjghiVVGaJe6dBRLiiB3Lf-RTTNlQbqEe_O7t0E,1068
7
+ gist_select-0.1.0.dist-info/METADATA,sha256=xJtdlwLr-3s2pEK5hiTfN5dlYeob0B9uGrFTwbP1mAU,12929
8
+ gist_select-0.1.0.dist-info/WHEEL,sha256=YCfwYGOYMi5Jhw2fU4yNgwErybb2IX5PEwBKV4ZbdBo,91
9
+ gist_select-0.1.0.dist-info/top_level.txt,sha256=OqhjQFfv8zvbaMBjq4e9tSSfb5QAbpyMS4klhBZz5s8,5
10
+ gist_select-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Kenny Claka
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ gist