Repository navigation
Expand file tree
/
Copy pathtest_builder.py
More file actions
312 lines (247 loc) · 12 KB
/
Copy pathtest_builder.py
File metadata and controls
312 lines (247 loc) · 12 KB
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
import numpy as np
import pytest
import deglib
from deglib.distances import FloatSpace, Metric
class CallbackTester:
def __init__(self):
self.num_callbacks = 0
self.last_status = None
def __call__(self, status: deglib.BuilderStatus):
assert isinstance(status, deglib.BuilderStatus), (
'Got instance of type "{}" for builder_status in callback'.format(type(status))
)
self.last_status = status
self.num_callbacks += 1
class TestGraphs:
def setup_method(self):
self.samples = 100
self.dims = 128
self.edges_per_vertex = self.samples // 10
self.data = np.random.random((self.samples, self.dims)).astype(np.float32)
@pytest.mark.parametrize("batch", [True, False])
def test_add_entry(self, batch):
graph = deglib.create_empty(
self.data.shape[0], FloatSpace.create(self.data.shape[1], Metric.FP32_L2), self.edges_per_vertex
)
builder = deglib.GraphBuilder(graph, extend_k=30, extend_eps=0.2, improve_k=30)
if batch:
builder.add_entry(range(self.data.shape[0]), self.data)
else:
for i, vec in enumerate(self.data):
vec: np.ndarray
builder.add_entry(i, vec)
@pytest.mark.parametrize("optimization_target", list(deglib.builder.OptimizationTarget))
def test_build_simple(self, optimization_target):
graph = deglib.create_empty(
self.data.shape[0], FloatSpace.create(self.data.shape[1], Metric.FP32_L2), self.edges_per_vertex
)
builder = deglib.GraphBuilder(
graph, extend_k=30, extend_eps=0.2, improve_k=30, optimization_target=optimization_target
)
for i, vec in enumerate(self.data):
vec: np.ndarray
builder.add_entry(i, vec)
builder.build()
@pytest.mark.parametrize("optimization_target", list(deglib.builder.OptimizationTarget))
def test_build_batch(self, optimization_target):
graph = deglib.create_empty(
self.data.shape[0], FloatSpace.create(self.data.shape[1], Metric.FP32_L2), self.edges_per_vertex
)
builder = deglib.GraphBuilder(
graph, extend_k=30, extend_eps=0.2, improve_k=30, optimization_target=optimization_target
)
builder.add_entry(range(self.data.shape[0]), self.data)
builder.build()
def test_build_with_remove(self):
graph = deglib.create_empty(
self.data.shape[0], FloatSpace.create(self.data.shape[1], Metric.FP32_L2), self.edges_per_vertex
)
builder = deglib.GraphBuilder(graph, extend_k=30, extend_eps=0.2, improve_k=30)
for label, vec in enumerate(self.data):
vec: np.ndarray
builder.add_entry(label, vec)
# remove half of the vertices
for label in range(0, self.data.shape[0], 2):
builder.remove_entry(label)
builder.build()
def test_get_num_entries(self):
graph = deglib.create_empty(
self.data.shape[0], FloatSpace.create(self.data.shape[1], Metric.FP32_L2), self.edges_per_vertex
)
builder = deglib.GraphBuilder(graph, extend_k=30, extend_eps=0.2, improve_k=30)
def _check_entries(expected: int, action: str):
assert action in ("new", "remove")
actual = builder.get_num_new_entries() if action == "new" else builder.get_num_remove_entries()
assert actual == expected, "Added {} {} entries, but get_num_{}_entries() returned {}".format(
expected, action, action, builder.get_num_new_entries()
)
_check_entries(0, "new")
_check_entries(0, "remove")
for label, vec in enumerate(self.data):
vec: np.ndarray
builder.add_entry(label, vec)
_check_entries(self.data.shape[0], "new")
_check_entries(0, "remove")
# remove half of the vertices
for label in range(0, self.data.shape[0], 2):
builder.remove_entry(label)
_check_entries(self.data.shape[0] // 2, "remove")
def test_callback(self):
graph = deglib.create_empty(
self.data.shape[0], FloatSpace.create(self.data.shape[1], Metric.FP32_L2), self.edges_per_vertex
)
builder = deglib.GraphBuilder(graph, extend_k=30, extend_eps=0.2, improve_k=30)
builder.add_entry(range(self.data.shape[0]), self.data)
tester = CallbackTester()
builder.build(callback=tester)
assert tester.num_callbacks > 0, "Expected at least 1 callback execution"
assert tester.last_status is not None
assert tester.last_status.step > 0
def test_concurrency_settings(self):
graph = deglib.create_empty(
self.data.shape[0], FloatSpace.create(self.data.shape[1], Metric.FP32_L2), self.edges_per_vertex
)
builder = deglib.GraphBuilder(graph, extend_k=30, extend_eps=0.2, improve_k=30)
# Test thread count
builder.set_thread_count(2)
# Test batch size setting and getting
builder.set_batch_size(tasks_per_batch=16, task_size=5)
expected_batch_size = 2 * 16 * 5
assert builder.get_batch_size() == expected_batch_size
builder.add_entry(range(self.data.shape[0]), self.data)
builder.build()
def test_stop(self):
graph = deglib.create_empty(
self.data.shape[0], FloatSpace.create(self.data.shape[1], Metric.FP32_L2), self.edges_per_vertex
)
builder = deglib.GraphBuilder(graph, extend_k=30, extend_eps=0.2, improve_k=30)
builder.add_entry(range(self.data.shape[0]), self.data)
stopped_in_callback = False
def _stopping_callback(status: deglib.BuilderStatus):
nonlocal stopped_in_callback
stopped_in_callback = True
builder.stop()
builder.build(callback=_stopping_callback)
assert stopped_in_callback
def test_build_returns_status(self):
graph = deglib.create_empty(
self.data.shape[0], FloatSpace.create(self.data.shape[1], Metric.FP32_L2), self.edges_per_vertex
)
builder = deglib.GraphBuilder(graph, extend_k=30, extend_eps=0.2, improve_k=30)
builder.add_entry(range(self.data.shape[0]), self.data)
status = builder.build()
assert isinstance(status, deglib.BuilderStatus), "Expected BuilderStatus, got {}".format(type(status))
assert status.added == self.data.shape[0]
assert status.deleted == 0
assert len(status.total_added_ids) == self.data.shape[0]
assert len(status.total_deleted_ids) == 0
def test_show_progress(self):
graph = deglib.create_empty(
self.data.shape[0], FloatSpace.create(self.data.shape[1], Metric.FP32_L2), self.edges_per_vertex
)
builder = deglib.GraphBuilder(graph, extend_k=30, extend_eps=0.2, improve_k=30)
builder.add_entry(range(self.data.shape[0]), self.data)
status = builder.build(show_progress=True)
assert isinstance(status, deglib.BuilderStatus)
assert status.added == self.data.shape[0]
def test_builder_status_facade_exposed(self):
assert hasattr(deglib, "BuilderStatus")
assert hasattr(deglib.builder, "BuilderStatus")
def test_build_status_callback_step_ids(self):
graph = deglib.create_empty(
self.data.shape[0], FloatSpace.create(self.data.shape[1], Metric.FP32_L2), self.edges_per_vertex
)
builder = deglib.GraphBuilder(graph, extend_k=30, extend_eps=0.2, improve_k=30)
builder.add_entry(range(self.data.shape[0]), self.data)
callback_statuses = []
def _collect_callback(status: deglib.BuilderStatus):
callback_statuses.append(status)
result = builder.build(callback=_collect_callback)
assert len(callback_statuses) > 0
# Verify that total_added_ids grows monotonically across callbacks
prev_total = 0
for cb_status in callback_statuses:
assert len(cb_status.total_added_ids) >= prev_total
assert len(cb_status.step_added_ids) > 0 or cb_status.added == 0
prev_total = len(cb_status.total_added_ids)
# The last callback's total should match the return value
last_cb = callback_statuses[-1]
assert last_cb.total_added_ids == result.total_added_ids
assert last_cb.total_deleted_ids == result.total_deleted_ids
def test_build_mixed_add_delete(self):
graph = deglib.create_empty(
self.data.shape[0], FloatSpace.create(self.data.shape[1], Metric.FP32_L2), self.edges_per_vertex
)
builder = deglib.GraphBuilder(graph, extend_k=30, extend_eps=0.2, improve_k=30)
for label, vec in enumerate(self.data):
vec: np.ndarray
builder.add_entry(label, vec)
# remove some vertices
for label in range(0, self.data.shape[0], 3):
builder.remove_entry(label)
status = builder.build()
assert isinstance(status, deglib.BuilderStatus)
assert status.added == self.data.shape[0]
assert status.deleted > 0
assert len(status.total_added_ids) == self.data.shape[0]
assert len(status.total_deleted_ids) > 0
@pytest.mark.parametrize("dim", [48, 80, 100, 784])
@pytest.mark.parametrize("metric", [Metric.FP32_L2, Metric.FP32_InnerProduct])
def test_build_unaligned_dimensions(self, dim, metric):
samples = 60
edges_per_vertex = 16
np.random.seed(42)
data = np.random.random((samples, dim)).astype(np.float32)
if metric == Metric.FP32_InnerProduct:
data = data / np.linalg.norm(data, axis=1, keepdims=True)
graph = deglib.create_empty(samples, FloatSpace.create(dim, metric), edges_per_vertex)
builder = deglib.GraphBuilder(
graph,
extend_k=32,
extend_eps=0.1,
optimization_target=deglib.builder.OptimizationTarget.LowLID if metric == Metric.FP32_L2 else deglib.builder.OptimizationTarget.HighLID,
)
builder.add_entry(range(samples), data)
status = builder.build()
assert status.added == samples
assert graph.size() == samples
# Verify search works and returns valid neighbors
res = graph.search(data[0], k=10, eps_or_ef=0.1)
indices, dists = res
assert len(indices) == 10
assert not np.isnan(dists).any()
def test_sliding_window_continuous_updates(self):
window_size = 50
batch_size = 10
rounds = 5
dims = 16
edges_per_vertex = 8
np.random.seed(42)
total_vectors = window_size + batch_size * rounds
all_data = np.random.random((total_vectors, dims)).astype(np.float32)
graph = deglib.create_empty(window_size + batch_size * 2, FloatSpace.create(dims, Metric.FP32_L2), edges_per_vertex)
builder = deglib.GraphBuilder(graph, extend_k=16, extend_eps=0.1, improve_k=8, optimization_target=deglib.builder.OptimizationTarget.LowLID)
# Initial build
builder.add_entry(range(window_size), all_data[:window_size])
builder.build()
assert graph.size() == window_size
active_start = 0
next_insert = window_size
for r in range(rounds):
# Remove oldest
for lbl in range(active_start, active_start + batch_size):
builder.remove_entry(lbl)
# Add newest
new_labels = list(range(next_insert, next_insert + batch_size))
new_data = all_data[next_insert : next_insert + batch_size]
builder.add_entry(new_labels, new_data)
builder.build()
active_start += batch_size
next_insert += batch_size
assert graph.size() == window_size
# Test search on latest added vector
query = all_data[next_insert - 1]
indices, dists = graph.search(query, k=1, eps_or_ef=0.1)
assert len(indices) == 1
assert indices[0] == next_insert - 1
assert np.isclose(dists[0], 0.0, atol=1e-5)