sparsetrace commited on
Commit
20ea795
·
verified ·
1 Parent(s): 4b98153

Create ann.py

Browse files
Files changed (1) hide show
  1. ann.py +302 -0
ann.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # src/dima/ann.py
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ from typing import Any, Dict, Optional, Tuple
6
+
7
+ import numpy as np
8
+
9
+ from .utils import as_contig_f32, sqdist_ab
10
+
11
+
12
+ # -------------------------
13
+ # Public API
14
+ # -------------------------
15
+ ANNBackend = str # "auto" | "faiss" | "pynndescent" | "sklearn" | "brute"
16
+
17
+
18
+ class ANNBase:
19
+ """Minimal ANN interface used by DMAP/GPLM."""
20
+ def build(self, X: np.ndarray) -> "ANNBase":
21
+ raise NotImplementedError
22
+
23
+ def search(self, Q: np.ndarray, k: int) -> Tuple[np.ndarray, np.ndarray]:
24
+ """
25
+ Returns:
26
+ idx: (B,k) int64
27
+ D2 : (B,k) float32 (squared Euclidean distances)
28
+ """
29
+ raise NotImplementedError
30
+
31
+
32
+ def make_ann(
33
+ backend: ANNBackend = "auto",
34
+ ann_params: Optional[Dict[str, Any]] = None,
35
+ n_jobs: int = -1,
36
+ ) -> Tuple[ANNBase, str]:
37
+ """
38
+ Create an ANN implementation.
39
+
40
+ backend:
41
+ - "auto": prefers faiss, then pynndescent, then sklearn, else brute
42
+ - "faiss": FAISS (if installed)
43
+ - "pynndescent": NNDescent (if installed)
44
+ - "sklearn": sklearn NearestNeighbors (if installed)
45
+ - "brute": exact brute force
46
+
47
+ ann_params:
48
+ - for faiss:
49
+ index: "flat" | "hnsw" | "ivf_flat"
50
+ hnsw_M: int (default 32)
51
+ ef_search: int (default 64)
52
+ ef_construction: int (default 200)
53
+ ivf_nlist: int (default 1024)
54
+ ivf_nprobe: int (default 16)
55
+ use_float16: bool (default False; GPU only typically)
56
+ - for pynndescent:
57
+ n_trees: int
58
+ n_iters: int
59
+ metric: str (default "euclidean")
60
+ - for sklearn:
61
+ algorithm: str (default "auto")
62
+ leaf_size: int (default 40)
63
+ metric: str (default "euclidean")
64
+ """
65
+ ann_params = {} if ann_params is None else dict(ann_params)
66
+ b = (backend or "auto").lower()
67
+
68
+ if b == "auto":
69
+ for cand in ("faiss", "pynndescent", "sklearn", "brute"):
70
+ ann, used = make_ann(cand, ann_params=ann_params, n_jobs=n_jobs)
71
+ if used != "brute" or cand == "brute":
72
+ return ann, used
73
+ return BruteANN(), "brute"
74
+
75
+ if b == "faiss":
76
+ try:
77
+ return FaissANN(ann_params=ann_params), "faiss"
78
+ except Exception as e:
79
+ raise ImportError(
80
+ "FAISS backend requested but faiss is not available or failed to initialize. "
81
+ "Install with: pip install dima[faiss]"
82
+ ) from e
83
+
84
+ if b == "pynndescent":
85
+ try:
86
+ return PyNNDescentANN(ann_params=ann_params), "pynndescent"
87
+ except Exception as e:
88
+ raise ImportError(
89
+ "pynndescent backend requested but pynndescent is not available. "
90
+ "Install with: pip install pynndescent"
91
+ ) from e
92
+
93
+ if b == "sklearn":
94
+ try:
95
+ return SklearnANN(n_jobs=n_jobs, ann_params=ann_params), "sklearn"
96
+ except Exception as e:
97
+ raise ImportError(
98
+ "sklearn backend requested but scikit-learn is not available. "
99
+ "Install with: pip install scikit-learn"
100
+ ) from e
101
+
102
+ if b == "brute":
103
+ return BruteANN(), "brute"
104
+
105
+ raise ValueError(f"Unknown ANN backend: {backend!r}")
106
+
107
+
108
+ # -------------------------
109
+ # Brute-force (no deps)
110
+ # -------------------------
111
+ class BruteANN(ANNBase):
112
+ def __init__(self):
113
+ self.X = None
114
+
115
+ def build(self, X: np.ndarray) -> "BruteANN":
116
+ self.X = as_contig_f32(X)
117
+ return self
118
+
119
+ def search(self, Q: np.ndarray, k: int) -> Tuple[np.ndarray, np.ndarray]:
120
+ if self.X is None:
121
+ raise RuntimeError("BruteANN.search called before build().")
122
+ X = self.X
123
+ Q = as_contig_f32(Q)
124
+ k = int(k)
125
+ if k <= 0:
126
+ raise ValueError("k must be >= 1")
127
+ if k > X.shape[0]:
128
+ k = X.shape[0]
129
+
130
+ D2 = sqdist_ab(Q, X) # (B,N)
131
+ idx = np.argpartition(D2, kth=k - 1, axis=1)[:, :k]
132
+ rows = np.arange(Q.shape[0])[:, None]
133
+ d2 = D2[rows, idx]
134
+
135
+ # sort within k
136
+ ordk = np.argsort(d2, axis=1)
137
+ idx = idx[rows, ordk].astype(np.int64)
138
+ d2 = d2[rows, ordk].astype(np.float32)
139
+ return idx, d2
140
+
141
+
142
+ # -------------------------
143
+ # FAISS
144
+ # -------------------------
145
+ class FaissANN(ANNBase):
146
+ def __init__(self, ann_params: Optional[Dict[str, Any]] = None):
147
+ self.ann_params = {} if ann_params is None else dict(ann_params)
148
+ self.index = None
149
+ self.X = None # keep reference for possible rebuild
150
+
151
+ # delayed import
152
+ import faiss # type: ignore
153
+ self.faiss = faiss
154
+
155
+ def _build_index(self, d: int):
156
+ p = self.ann_params
157
+ faiss = self.faiss
158
+
159
+ index_kind = str(p.get("index", "flat")).lower()
160
+
161
+ if index_kind == "flat":
162
+ index = faiss.IndexFlatL2(d)
163
+
164
+ elif index_kind == "hnsw":
165
+ M = int(p.get("hnsw_M", 32))
166
+ index = faiss.IndexHNSWFlat(d, M)
167
+ # optional tuning
168
+ ef_search = int(p.get("ef_search", 64))
169
+ ef_constr = int(p.get("ef_construction", 200))
170
+ index.hnsw.efSearch = ef_search
171
+ index.hnsw.efConstruction = ef_constr
172
+
173
+ elif index_kind == "ivf_flat":
174
+ nlist = int(p.get("ivf_nlist", 1024))
175
+ quantizer = faiss.IndexFlatL2(d)
176
+ index = faiss.IndexIVFFlat(quantizer, d, nlist, faiss.METRIC_L2)
177
+ nprobe = int(p.get("ivf_nprobe", 16))
178
+ index.nprobe = nprobe
179
+
180
+ else:
181
+ raise ValueError(f"Unknown faiss index kind: {index_kind!r}")
182
+
183
+ return index
184
+
185
+ def build(self, X: np.ndarray) -> "FaissANN":
186
+ X = as_contig_f32(X)
187
+ self.X = X
188
+ faiss = self.faiss
189
+ d = int(X.shape[1])
190
+
191
+ index = self._build_index(d)
192
+
193
+ # IVF needs training
194
+ if hasattr(index, "is_trained") and not index.is_trained:
195
+ index.train(X)
196
+
197
+ index.add(X)
198
+ self.index = index
199
+ return self
200
+
201
+ def search(self, Q: np.ndarray, k: int) -> Tuple[np.ndarray, np.ndarray]:
202
+ if self.index is None:
203
+ raise RuntimeError("FaissANN.search called before build().")
204
+ Q = as_contig_f32(Q)
205
+ k = int(k)
206
+ if k <= 0:
207
+ raise ValueError("k must be >= 1")
208
+
209
+ # FAISS returns (distances, indices); for L2 these are squared distances
210
+ D2, I = self.index.search(Q, k)
211
+ return I.astype(np.int64), D2.astype(np.float32)
212
+
213
+
214
+ # -------------------------
215
+ # PyNNDescent
216
+ # -------------------------
217
+ class PyNNDescentANN(ANNBase):
218
+ def __init__(self, ann_params: Optional[Dict[str, Any]] = None):
219
+ self.ann_params = {} if ann_params is None else dict(ann_params)
220
+ self.index = None
221
+ self.X = None
222
+
223
+ from pynndescent import NNDescent # type: ignore
224
+ self.NNDescent = NNDescent
225
+
226
+ def build(self, X: np.ndarray) -> "PyNNDescentANN":
227
+ X = as_contig_f32(X)
228
+ self.X = X
229
+ p = self.ann_params
230
+
231
+ metric = p.get("metric", "euclidean")
232
+ n_trees = p.get("n_trees", None)
233
+ n_iters = p.get("n_iters", None)
234
+
235
+ kwargs: Dict[str, Any] = {"metric": metric}
236
+ if n_trees is not None:
237
+ kwargs["n_trees"] = int(n_trees)
238
+ if n_iters is not None:
239
+ kwargs["n_iters"] = int(n_iters)
240
+
241
+ self.index = self.NNDescent(X, **kwargs)
242
+ return self
243
+
244
+ def search(self, Q: np.ndarray, k: int) -> Tuple[np.ndarray, np.ndarray]:
245
+ if self.index is None:
246
+ raise RuntimeError("PyNNDescentANN.search called before build().")
247
+ Q = as_contig_f32(Q)
248
+ k = int(k)
249
+ if k <= 0:
250
+ raise ValueError("k must be >= 1")
251
+
252
+ # NNDescent returns (indices, distances) with euclidean distances (not squared)
253
+ I, d = self.index.query(Q, k=k)
254
+ D2 = (d.astype(np.float32) ** 2)
255
+ return I.astype(np.int64), D2
256
+
257
+
258
+ # -------------------------
259
+ # scikit-learn NearestNeighbors
260
+ # -------------------------
261
+ class SklearnANN(ANNBase):
262
+ def __init__(self, n_jobs: int = -1, ann_params: Optional[Dict[str, Any]] = None):
263
+ self.ann_params = {} if ann_params is None else dict(ann_params)
264
+ self.n_jobs = int(n_jobs)
265
+ self.nn = None
266
+ self.X = None
267
+
268
+ from sklearn.neighbors import NearestNeighbors # type: ignore
269
+ self.NearestNeighbors = NearestNeighbors
270
+
271
+ def build(self, X: np.ndarray) -> "SklearnANN":
272
+ X = as_contig_f32(X)
273
+ self.X = X
274
+ p = self.ann_params
275
+
276
+ algorithm = p.get("algorithm", "auto")
277
+ leaf_size = int(p.get("leaf_size", 40))
278
+ metric = p.get("metric", "euclidean")
279
+
280
+ self.nn = self.NearestNeighbors(
281
+ n_neighbors=1, # set later in search
282
+ algorithm=algorithm,
283
+ leaf_size=leaf_size,
284
+ metric=metric,
285
+ n_jobs=self.n_jobs,
286
+ )
287
+ self.nn.fit(X)
288
+ return self
289
+
290
+ def search(self, Q: np.ndarray, k: int) -> Tuple[np.ndarray, np.ndarray]:
291
+ if self.nn is None:
292
+ raise RuntimeError("SklearnANN.search called before build().")
293
+ Q = as_contig_f32(Q)
294
+ k = int(k)
295
+ if k <= 0:
296
+ raise ValueError("k must be >= 1")
297
+
298
+ self.nn.set_params(n_neighbors=k)
299
+ d, I = self.nn.kneighbors(Q, return_distance=True)
300
+ # sklearn distances are euclidean; square them
301
+ D2 = (d.astype(np.float32) ** 2)
302
+ return I.astype(np.int64), D2