Repository navigation
Expand file tree
/
Copy pathbuilder.py
More file actions
451 lines (375 loc) · 18.4 KB
/
Copy pathbuilder.py
File metadata and controls
451 lines (375 loc) · 18.4 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
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
import enum
import sys
import time
from collections.abc import Callable, Iterable
import deglib_cpp
import numpy as np
from .cpu import InstructionSet
from .distances import FloatSpace, Metric
from .graph import DynamicExplorationGraph, create_empty
from .utils import InvalidShapeException, assure_array
class OptimizationTarget(enum.IntEnum):
"""
Information about the data distribution to help switch between different graph extension strategies.
- StreamingData: Optimized for streaming or shifting distributions
- HighLID: Optimized for datasets with high local intrinsic dimensionality (above 15)
- LowLID: Optimized for datasets with low local intrinsic dimensionality (below 15)
"""
StreamingData = deglib_cpp.OptimizationTarget.StreamingData
HighLID = deglib_cpp.OptimizationTarget.HighLID
LowLID = deglib_cpp.OptimizationTarget.LowLID
class BuilderStatus:
"""
Snapshot of the graph build progress.
Instances are created internally and passed to the ``callback`` of
:meth:`GraphBuilder.build`, and returned by :meth:`GraphBuilder.build`.
This facade wraps the native status object so that end users never have to
interact with the ``deglib_cpp`` bindings directly.
The instance handed to a progress ``callback`` is only valid for the
duration of that callback invocation.
"""
def __init__(self, status_cpp: deglib_cpp.BuilderStatus):
self._status_cpp = status_cpp
@property
def step(self) -> int:
"""Number of graph manipulation steps completed."""
return self._status_cpp.step
@property
def added(self) -> int:
"""Total number of vertices added so far."""
return self._status_cpp.added
@property
def deleted(self) -> int:
"""Total number of vertices deleted so far."""
return self._status_cpp.deleted
@property
def improved(self) -> int:
"""Total number of successful edge improvements so far."""
return self._status_cpp.improved
@property
def tries(self) -> int:
"""Total number of improvement attempts so far."""
return self._status_cpp.tries
@property
def step_added_ids(self):
"""External labels added during the current build step."""
return self._status_cpp.step_added_ids
@property
def step_deleted_ids(self):
"""External labels deleted during the current build step."""
return self._status_cpp.step_deleted_ids
@property
def total_added_ids(self):
"""All external labels added across the entire build."""
return self._status_cpp.total_added_ids
@property
def total_deleted_ids(self):
"""All external labels deleted across the entire build."""
return self._status_cpp.total_deleted_ids
def __repr__(self) -> str:
return (
f"BuilderStatus(step={self.step}, added={self.added}, deleted={self.deleted}, "
f"improved={self.improved}, tries={self.tries})"
)
class GraphBuilder:
"""
Constructs a GraphBuilder for building and optimizing a regular graph.
This class provides functionality to incrementally build and optimize a graph structure
by adding/removing vertices and improving edge connections through various strategies.
"""
def __init__(
self,
graph: DynamicExplorationGraph,
seed: int | None = None,
optimization_target: OptimizationTarget = OptimizationTarget.LowLID,
extend_k: int = 0,
extend_eps: float = 0.1,
improve_k: int = 0,
improve_eps: float = 0.001,
max_path_length: int = 5,
improve_tries: int = 0,
):
"""
Initialize a GraphBuilder with the specified parameters.
:param graph: The preallocated mutable DynamicExplorationGraph to build and optimize
:type graph: DynamicExplorationGraph
:param seed: Random seed used for randomized operations. If None, a default seed is used.
:type seed: int | None
:param optimization_target: Optimization strategy based on data distribution characteristics
:type optimization_target: OptimizationTarget
:param extend_k: Number of neighbors to consider when extending the graph (must be > edges_per_vertex).
Defaults to ``edges_per_vertex * 2`` if 0 or <= edges_per_vertex.
:param extend_eps: Epsilon value for neighbor search during graph extension (default: 0.1)
:param improve_k: Number of neighbors to consider when improving the graph
:param improve_eps: Epsilon value for neighbor search during graph improvement
:param max_path_length: Maximum number of edge swaps in a single improvement attempt
:param improve_tries: Number of improvement attempts per build step
"""
if extend_k <= graph.get_edges_per_vertex():
extend_k = graph.get_edges_per_vertex() * 2
self.builder_cpp = deglib_cpp.GraphBuilder(
graph.dynamic_exploration_graph_cpp,
seed,
deglib_cpp.OptimizationTarget(int(optimization_target)),
extend_k,
extend_eps,
improve_k,
improve_eps,
max_path_length,
improve_tries,
)
self.graph = graph
self.optimization_target = optimization_target
def add_entry(self, external_label: int | Iterable[int] | np.ndarray, feature: np.ndarray):
"""
Provide the builder with new entries to be added to the graph during the build process.
Can add a single entry or a batch of entries. For batch processing, the feature array
should have shape [N, D] where N is the number of entries and D is the dimensionality.
:param external_label: The label(s) that name the added vertex/vertices. For batch processing,
should be a list or array with length N matching the number of features
:param feature: The feature vector(s) to be added. Shape [D] for single entry or [N, D] for batch
:raises InvalidShapeException: If feature array has invalid shape (not 1D or 2D)
:raises ValueError: If number of features doesn't match number of labels in batch processing
"""
# standardize feature shape
if len(feature.shape) == 1:
feature = feature.reshape(1, -1)
if len(feature.shape) != 2:
raise InvalidShapeException(f"invalid feature shape: {feature.shape}")
valid_dtype = self.graph.get_feature_space().metric().get_dtype()
feature = assure_array(feature, "feature", valid_dtype)
# standardize external label
if isinstance(external_label, int):
external_label = np.array([external_label], dtype=np.uint32)
elif isinstance(external_label, Iterable) and not isinstance(external_label, np.ndarray):
external_label = np.array(external_label, dtype=np.uint32)
assure_array(external_label, "external_label", np.uint32)
if feature.shape[0] != external_label.shape[0]:
raise ValueError(f"Got {feature.shape[0]} features, but {external_label.shape[0]} labels")
self.builder_cpp.add_entry(external_label, feature)
def remove_entry(self, external_label: int):
"""
Command the builder to remove a vertex from the graph as quickly as possible.
:param external_label: The external label that identifies the graph vertex to remove
:type external_label: int
"""
self.builder_cpp.remove_entry(external_label)
def get_num_new_entries(self) -> int:
"""
Get the number of entries that will be added to the graph.
:return: Number of entries queued for addition
:rtype: int
"""
return self.builder_cpp.get_num_new_entries()
def get_num_remove_entries(self) -> int:
"""
Get the number of entries that will be removed from the graph.
:return: Number of entries queued for removal
:rtype: int
"""
return self.builder_cpp.get_num_remove_entries()
def set_thread_count(self, thread_count: int):
"""
Set the number of threads used to extend the graph during building.
When the thread count is greater than 1 and the optimization target is not StreamingData,
the builder will utilize multiple threads to add elements to the graph in parallel.
By default, all available CPU cores/threads are used unless specified.
Note: The order in which elements are added is not guaranteed when using multiple threads.
:param thread_count: Number of threads to use for graph extension
:type thread_count: int
"""
return self.builder_cpp.set_thread_count(thread_count)
def set_batch_size(self, tasks_per_batch: int, task_size: int):
"""
Set the batch size parameters for parallel graph construction.
The builder processes elements in batches to minimize synchronization between threads.
The total batch size is calculated as:
batch_size = thread_count * tasks_per_batch * task_size
Effects of thread count and batch size:
- thread_count = 1 and batch_size = 1: low throughput, medium latency, order of elements is guaranteed
- thread_count > 1 and batch_size = 1: high throughput, low latency, order of elements is not guaranteed
- thread_count > 1 and batch_size > 1: highest throughput, highest latency, order of elements is not
guaranteed
Note: The optimization target `StreamingData` always uses a thread count of 1.
:param tasks_per_batch: Number of tasks for each thread in one batch (default: 32).
:type tasks_per_batch: int
:param task_size: Number of elements each thread processes in one task (default: 10).
:type task_size: int
"""
return self.builder_cpp.set_batch_size(tasks_per_batch, task_size)
def get_batch_size(self) -> int:
"""
Get the current batch size used for parallel graph construction.
:return: The current batch size
:rtype: int
"""
return self.builder_cpp.get_batch_size()
def build(
self,
callback: Callable[[BuilderStatus], None] | None = None,
show_progress: bool = False,
infinite: bool = False,
) -> BuilderStatus:
"""
Build the graph. This could be run on a separate thread in an infinite loop. Call stop() to end this process.
:param callback: The callback that is called after each step of the build process. A BuilderStatus
is the only argument to the function. If None nothing is printed.
:param show_progress: If True and no callback is given, a simple progress bar is printed to stdout.
Ignored when running in infinite mode (total workload is unknown).
:param infinite: If set to True, blocks indefinitely, until the stop() function is called. Can be used, if
build() is run in a separate thread.
:return: BuilderStatus containing build metrics and ID vectors for added/deleted vertices.
:rtype: BuilderStatus
"""
if callback is None and show_progress and not infinite:
callback = ProgressCallback(self.get_num_new_entries(), self.get_num_remove_entries())
if callback is None:
return BuilderStatus(self.builder_cpp.build_silent(infinite))
def _callback(status_cpp) -> None:
callback(BuilderStatus(status_cpp))
return BuilderStatus(self.builder_cpp.build(_callback, infinite))
def stop(self):
"""
Stop the build process.
The build process can only be stopped between steps, not during step execution.
"""
self.builder_cpp.stop()
def __repr__(self):
"""
Return a string representation of the GraphBuilder.
:return: String representation showing the number of vertices added
:rtype: str
"""
return f"GraphBuilder(vertices_added={self.graph.size()})"
def build_from_data(
data: np.ndarray,
labels: Iterable[int] | np.ndarray | None = None,
edges_per_vertex: int = 32,
capacity: int = -1,
metric: Metric | str = Metric.FP32_L2,
instruction: InstructionSet | str = InstructionSet.Auto,
seed: int | None = None,
optimization_target: OptimizationTarget = OptimizationTarget.LowLID,
extend_k: int = 0,
extend_eps: float = 0.1,
improve_k: int = 0,
improve_eps: float = 0.001,
max_path_length: int = 5,
improve_tries: int = 0,
thread_count: int = 0,
callback: Callable[[BuilderStatus], None] | None = None,
show_progress: bool = False,
) -> DynamicExplorationGraph:
"""
Create a new graph built from the given data using a GraphBuilder.
This is a convenience function that creates a graph, builder, adds all data entries,
and builds the complete graph in one call. Infinite building is not supported.
:param data: Feature data with shape [N, D] where N is number of samples, D is dimensionality
:type data: np.ndarray
:param labels: Labels for each data entry with shape [N]. If None, labels 0 to N-1 are created.
If numpy array, should have dtype uint32
:type labels: Iterable[int] | np.ndarray | None
:param edges_per_vertex: Number of edges per vertex in the graph
:type edges_per_vertex: int
:param capacity: Maximum number of vertices the graph can hold. If <= 0, defaults to data.shape[0]
:type capacity: int
:param metric: Distance metric for measuring feature similarity
:type metric: Metric | str
:param instruction: CPU Instruction Set to use for SIMD vector distance computation
:type instruction: InstructionSet | str
:param seed: Random seed. If None, a default seed is used.
:type seed: int | None
:param optimization_target: Optimization strategy based on data distribution characteristics
:type optimization_target: OptimizationTarget
:param extend_k: Number of neighbors to consider when extending the graph (must be > edges_per_vertex).
Defaults to ``edges_per_vertex * 2``.
:type extend_k: int
:param extend_eps: Epsilon value for neighbor search during graph extension (default: 0.1)
:type extend_eps: float
:param improve_k: Number of neighbors to consider when improving the graph
:type improve_k: int
:param improve_eps: Epsilon value for neighbor search during graph improvement
:type improve_eps: float
:param max_path_length: Maximum number of edge swaps in a single improvement attempt
:type max_path_length: int
:param improve_tries: Number of improvement attempts per build step
:type improve_tries: int
:param thread_count: Number of threads to use for parallel building. If 0, uses hardware concurrency.
:type thread_count: int
:param callback: Callback function for build progress reporting, receiving a BuilderStatus. If None, nothing is reported.
:type callback: Callable[[BuilderStatus], None] | None
:param show_progress: If True and no callback is given, a simple progress bar is printed to stdout.
:type show_progress: bool
:return: The constructed and optimized graph
:rtype: DynamicExplorationGraph
"""
if capacity <= 0:
capacity = data.shape[0]
feature_space = FloatSpace.create(data.shape[1], metric, instruction)
graph = create_empty(capacity, feature_space, edges_per_vertex)
builder = GraphBuilder(
graph,
seed=seed,
optimization_target=optimization_target,
extend_k=extend_k,
extend_eps=extend_eps,
improve_k=improve_k,
improve_eps=improve_eps,
max_path_length=max_path_length,
improve_tries=improve_tries,
)
if labels is None:
labels = np.arange(data.shape[0], dtype=np.uint32)
builder.add_entry(labels, data)
if thread_count > 0:
builder.set_thread_count(thread_count)
builder.build(callback=callback, show_progress=show_progress)
return graph
class ProgressCallback:
"""
A callback class for displaying build progress as a progress bar.
Provides a visual progress bar showing the completion status of graph building operations,
including both addition and removal of entries.
"""
def __init__(
self, num_new_entries: int, num_remove_entries: int, bar_length: int = 60, min_print_interval: float = 0.1
):
"""
Initialize the progress callback with build parameters.
:param num_new_entries: Total number of entries to be added to the graph
:type num_new_entries: int
:param num_remove_entries: Total number of entries to be removed from the graph
:type num_remove_entries: int
:param bar_length: Length of the progress bar in characters
:type bar_length: int
:param min_print_interval: Minimum time interval between progress updates in seconds
:type min_print_interval: float
"""
self.num_new_entries = num_new_entries
self.num_remove_entries = num_remove_entries
self.bar_length = bar_length
self.maximal = self.num_new_entries + self.num_remove_entries
self.len_max = len(str(self.maximal))
self.last_print_time = 0
self.min_print_interval = min_print_interval
def __call__(self, builder_status: BuilderStatus):
"""
Display the current build progress as a formatted progress bar.
Called by the builder during the build process to report status. Updates are throttled
by min_print_interval to avoid excessive output, except for the final step.
:param builder_status: Current status of the build process containing step counts
:type builder_status: BuilderStatus
"""
current_time = time.time()
num_steps = builder_status.added + builder_status.deleted
last_step = num_steps == self.maximal
if current_time - self.last_print_time >= self.min_print_interval or last_step:
self.last_print_time = current_time
progress = num_steps / self.maximal
block = int(self.bar_length * progress)
bar = "#" * block + "-" * (self.bar_length - block)
percentage = progress * 100
sys.stdout.write(f"\r{percentage:6.2f}% [{bar}] ({num_steps:{self.len_max}} / {self.maximal})")
if last_step:
sys.stdout.write("\n") # newline at the end
sys.stdout.flush()