gist-select 0.1.0__tar.gz

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.
@@ -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,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