-
Notifications
You must be signed in to change notification settings - Fork 246
/
Copy pathtest_dynamic_memory_index.py
469 lines (433 loc) · 17.2 KB
/
test_dynamic_memory_index.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
import shutil
import tempfile
import unittest
import warnings
import diskannpy as dap
import numpy as np
from fixtures import build_random_vectors_and_memory_index
from sklearn.neighbors import NearestNeighbors
def _calculate_recall(
result_set_tags: np.ndarray,
original_indices_to_tags: np.ndarray,
truth_set_indices: np.ndarray,
recall_at: int = 5,
) -> float:
found = 0
for i in range(0, result_set_tags.shape[0]):
result_set_set = set(result_set_tags[i][0:recall_at])
truth_set_set = set()
for knn_index in truth_set_indices[i][0:recall_at]:
truth_set_set.add(
original_indices_to_tags[knn_index]
) # mapped into our tag number instead
found += len(result_set_set.intersection(truth_set_set))
return found / (result_set_tags.shape[0] * recall_at)
class TestDynamicMemoryIndex(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls._test_matrix = [
build_random_vectors_and_memory_index(np.float32, "l2", with_tags=True),
build_random_vectors_and_memory_index(np.uint8, "l2", with_tags=True),
build_random_vectors_and_memory_index(np.int8, "l2", with_tags=True),
build_random_vectors_and_memory_index(np.float32, "cosine", with_tags=True),
build_random_vectors_and_memory_index(np.uint8, "cosine", with_tags=True),
build_random_vectors_and_memory_index(np.int8, "cosine", with_tags=True),
build_random_vectors_and_memory_index(np.float32, "mips", with_tags=True),
]
cls._example_ann_dir = cls._test_matrix[0][4]
@classmethod
def tearDownClass(cls) -> None:
for test in cls._test_matrix:
try:
ann_dir = test[4]
shutil.rmtree(ann_dir, ignore_errors=True)
except:
pass
def test_recall_and_batch(self):
for (
metric,
dtype,
query_vectors,
index_vectors,
ann_dir,
vector_bin_file,
generated_tags,
) in self._test_matrix:
with self.subTest(msg=f"Testing dtype {dtype}"):
index = dap.DynamicMemoryIndex.from_file(
index_directory=ann_dir,
max_vectors=11_000,
complexity=64,
graph_degree=32,
num_threads=16,
)
k = 5
batch_response = index.batch_search(
query_vectors,
k_neighbors=k,
complexity=5,
num_threads=16,
)
self.assertIsInstance(batch_response, dap.QueryResponseBatch)
diskann_neighbors, diskann_distances = batch_response
if metric == "l2" or metric == "cosine":
knn = NearestNeighbors(
n_neighbors=100, algorithm="auto", metric=metric
)
knn.fit(index_vectors)
knn_distances, knn_indices = knn.kneighbors(query_vectors)
recall = _calculate_recall(
diskann_neighbors, generated_tags, knn_indices, k
)
self.assertTrue(
recall > 0.70,
f"Recall [{recall}] was not over 0.7",
)
def test_single(self):
for (
metric,
dtype,
query_vectors,
index_vectors,
ann_dir,
vector_bin_file,
generated_tags,
) in self._test_matrix:
with self.subTest(msg=f"Testing dtype {dtype}"):
index = dap.DynamicMemoryIndex(
distance_metric="l2",
vector_dtype=dtype,
dimensions=10,
max_vectors=11_000,
complexity=64,
graph_degree=32,
num_threads=16,
)
index.batch_insert(vectors=index_vectors, vector_ids=generated_tags)
k = 5
response = index.search(query_vectors[0], k_neighbors=k, complexity=5)
self.assertIsInstance(response, dap.QueryResponse)
ids, dists = response
self.assertEqual(ids.shape[0], k)
self.assertEqual(dists.shape[0], k)
def test_valid_metric(self):
with self.assertRaises(ValueError):
dap.DynamicMemoryIndex(
distance_metric="sandwich",
vector_dtype=np.single,
dimensions=10,
max_vectors=11_000,
complexity=64,
graph_degree=32,
num_threads=16,
)
with self.assertRaises(ValueError):
dap.DynamicMemoryIndex(
distance_metric=None,
vector_dtype=np.single,
dimensions=10,
max_vectors=11_000,
complexity=64,
graph_degree=32,
num_threads=16,
)
dap.DynamicMemoryIndex(
distance_metric="l2",
vector_dtype=np.single,
dimensions=10,
max_vectors=11_000,
complexity=64,
graph_degree=32,
num_threads=16,
)
dap.DynamicMemoryIndex(
distance_metric="mips",
vector_dtype=np.single,
dimensions=10,
max_vectors=11_000,
complexity=64,
graph_degree=32,
num_threads=16,
)
dap.DynamicMemoryIndex(
distance_metric="MiPs",
vector_dtype=np.single,
dimensions=10,
max_vectors=11_000,
complexity=64,
graph_degree=32,
num_threads=16,
)
def test_valid_vector_dtype(self):
aliases = {np.single: np.float32, np.byte: np.int8, np.ubyte: np.uint8}
for (
metric,
dtype,
query_vectors,
index_vectors,
ann_dir,
vector_bin_file,
generated_tags,
) in self._test_matrix:
with self.subTest():
index = dap.DynamicMemoryIndex(
distance_metric="l2",
vector_dtype=aliases[dtype],
dimensions=10,
max_vectors=11_000,
complexity=64,
graph_degree=32,
num_threads=16,
)
invalid = [np.double, np.float64, np.ulonglong]
for invalid_vector_dtype in invalid:
with self.subTest():
with self.assertRaises(ValueError, msg=invalid_vector_dtype):
dap.DynamicMemoryIndex(
distance_metric="l2",
vector_dtype=invalid_vector_dtype,
dimensions=10,
max_vectors=11_000,
complexity=64,
graph_degree=32,
num_threads=16,
)
def test_value_ranges_ctor(self):
(
metric,
dtype,
query_vectors,
index_vectors,
ann_dir,
vector_bin_file,
generated_tags,
) = build_random_vectors_and_memory_index(
np.single, "l2", with_tags=True, index_prefix="not_ann"
)
good_ranges = {
"distance_metric": "l2",
"vector_dtype": np.single,
"dimensions": 10,
"max_vectors": 11_000,
"complexity": 64,
"graph_degree": 32,
"max_occlusion_size": 10,
"alpha": 1.2,
"num_threads": 16,
"filter_complexity": 10,
"num_frozen_points": 10,
"initial_search_complexity": 32,
"search_threads": 0,
}
bad_ranges = {
"distance_metric": "l200000",
"vector_dtype": np.double,
"dimensions": -1,
"max_vectors": -1,
"complexity": 0,
"graph_degree": 0,
"max_occlusion_size": -1,
"alpha": -1,
"num_threads": -1,
"filter_complexity": -1,
"num_frozen_points": -1,
"initial_search_complexity": -1,
"search_threads": -1,
}
for bad_value_key in good_ranges.keys():
kwargs = good_ranges.copy()
kwargs[bad_value_key] = bad_ranges[bad_value_key]
with self.subTest():
with self.assertRaises(
ValueError,
msg=f"expected to fail with parameter {bad_value_key}={bad_ranges[bad_value_key]}",
):
index = dap.DynamicMemoryIndex(saturate_graph=False, **kwargs)
def test_value_ranges_search(self):
good_ranges = {"complexity": 5, "k_neighbors": 10}
bad_ranges = {"complexity": -1, "k_neighbors": 0}
for bad_value_key in good_ranges.keys():
kwargs = good_ranges.copy()
kwargs[bad_value_key] = bad_ranges[bad_value_key]
with self.subTest(msg=f"Test value ranges search with {kwargs=}"):
with self.assertRaises(ValueError):
index = dap.DynamicMemoryIndex.from_file(
index_directory=self._example_ann_dir,
num_threads=16,
initial_search_complexity=32,
max_vectors=10001,
complexity=64,
graph_degree=32,
)
index.search(query=np.array([], dtype=np.single), **kwargs)
def test_value_ranges_batch_search(self):
good_ranges = {
"complexity": 5,
"k_neighbors": 10,
"num_threads": 5,
}
bad_ranges = {
"complexity": 0,
"k_neighbors": 0,
"num_threads": -1,
}
for bad_value_key in good_ranges.keys():
kwargs = good_ranges.copy()
kwargs[bad_value_key] = bad_ranges[bad_value_key]
with self.subTest(msg=f"Testing value ranges batch search with {kwargs=}"):
with self.assertRaises(ValueError):
index = dap.DynamicMemoryIndex.from_file(
index_directory=self._example_ann_dir,
num_threads=16,
initial_search_complexity=32,
max_vectors=10001,
complexity=64,
graph_degree=32,
)
index.batch_search(
queries=np.array([[]], dtype=np.single), **kwargs
)
# Issue #400
def test_issue400(self):
_, _, _, index_vectors, ann_dir, _, generated_tags = self._test_matrix[0]
deletion_tag = generated_tags[10] # arbitrary choice
deletion_vector = index_vectors[10]
index = dap.DynamicMemoryIndex.from_file(
index_directory=ann_dir,
num_threads=16,
initial_search_complexity=32,
max_vectors=10100,
complexity=64,
graph_degree=32,
)
index.insert(np.array([1.0] * 10, dtype=np.single), 10099)
index.insert(np.array([2.0] * 10, dtype=np.single), 10050)
index.insert(np.array([3.0] * 10, dtype=np.single), 10053)
tags, distances = index.search(
np.array([3.0] * 10, dtype=np.single), k_neighbors=5, complexity=64
)
self.assertIn(10053, tags)
tags, distances = index.search(deletion_vector, k_neighbors=5, complexity=64)
self.assertIn(
deletion_tag, tags, "deletion_tag should exist, as we have not deleted yet"
)
index.mark_deleted(deletion_tag)
tags, distances = index.search(deletion_vector, k_neighbors=5, complexity=64)
self.assertNotIn(
deletion_tag,
tags,
"deletion_tag should not exist, as we have marked it for deletion",
)
with tempfile.TemporaryDirectory() as tmpdir:
index.save(tmpdir)
index2 = dap.DynamicMemoryIndex.from_file(
index_directory=tmpdir,
num_threads=16,
initial_search_complexity=32,
max_vectors=10100,
complexity=64,
graph_degree=32,
)
tags, distances = index2.search(
deletion_vector, k_neighbors=5, complexity=64
)
self.assertNotIn(
deletion_tag,
tags,
"deletion_tag should not exist, as we saved and reloaded the index without it",
)
def test_inserts_past_max_vectors(self):
def _tiny_index():
return dap.DynamicMemoryIndex(
distance_metric="l2",
vector_dtype=np.float32,
dimensions=10,
max_vectors=2,
complexity=64,
graph_degree=32,
num_threads=16,
)
rng = np.random.default_rng(12345)
# insert 3 vectors and look for an exception
index = _tiny_index()
index.insert(rng.random(10, dtype=np.float32), 1)
index.insert(rng.random(10, dtype=np.float32), 2)
with self.assertRaises(RuntimeError):
index.insert(rng.random(10, dtype=np.float32), 3)
# insert 2 vectors, delete 1, and insert another and expect a warning
index = _tiny_index()
index.insert(rng.random(10, dtype=np.float32), 1)
index.insert(rng.random(10, dtype=np.float32), 2)
index.mark_deleted(2)
with self.assertWarns(UserWarning):
self.assertEqual(index._removed_num_vectors, 1)
self.assertEqual(index._num_vectors, 2)
index.insert(rng.random(10, dtype=np.float32), 3)
self.assertEqual(index._removed_num_vectors, 0)
self.assertEqual(index._num_vectors, 2)
# insert 3 batch and look for an exception
index = _tiny_index()
with self.assertRaises(RuntimeError):
index.batch_insert(
rng.random((3, 10), dtype=np.float32),
np.array([1,2,3], dtype=np.uint32)
)
# insert 2 batch, remove 1, add 1 and expect a warning, remove 1, insert 2 batch and look for an exception
index = _tiny_index()
index.batch_insert(
rng.random((2, 10), dtype=np.float32),
np.array([1,2], dtype=np.uint32)
)
index.mark_deleted(1)
with self.assertWarns(UserWarning):
index.insert(rng.random(10, dtype=np.float32), 3)
index.mark_deleted(2)
with self.assertRaises(RuntimeError):
index.batch_insert(rng.random((2,10), dtype=np.float32), np.array([4, 5], dtype=np.uint32))
# insert 1, remove it, add 2 batch, and expect a warning
index = _tiny_index()
index.insert(rng.random(10, dtype=np.float32), 1)
index.mark_deleted(1)
with self.assertWarns(UserWarning):
index.batch_insert(rng.random((2, 10), dtype=np.float32), np.array([10, 20], dtype=np.uint32))
# insert 2 batch, remove both, add 2 batch, and expect a warning
index = _tiny_index()
index.batch_insert(rng.random((2,10), dtype=np.float32), np.array([10, 20], dtype=np.uint32))
index.mark_deleted(10)
index.mark_deleted(20)
with self.assertWarns(UserWarning):
index.batch_insert(rng.random((2, 10), dtype=np.float32), np.array([15, 25], dtype=np.uint32))
# insert 2 batch, remove both, consolidate_delete, add 2 batch and do not expect warning
index = _tiny_index()
index.batch_insert(rng.random((2,10), dtype=np.float32), np.array([10, 20], dtype=np.uint32))
index.mark_deleted(10)
index.mark_deleted(20)
index.consolidate_delete()
with warnings.catch_warnings():
warnings.simplefilter("error") # turns warnings into raised exceptions
index.batch_insert(rng.random((2, 10), dtype=np.float32), np.array([15, 25], dtype=np.uint32))
def test_zero_threads(self):
for (
metric,
dtype,
query_vectors,
index_vectors,
ann_dir,
vector_bin_file,
generated_tags,
) in self._test_matrix:
with self.subTest(msg=f"Testing dtype {dtype}"):
index = dap.DynamicMemoryIndex(
distance_metric="l2",
vector_dtype=dtype,
dimensions=10,
max_vectors=11_000,
complexity=64,
graph_degree=32,
num_threads=0, # explicitly asking it to use all available threads.
)
index.batch_insert(vectors=index_vectors, vector_ids=generated_tags, num_threads=0)
k = 5
ids, dists = index.batch_search(query_vectors, k_neighbors=k, complexity=5, num_threads=0)