forked from docarray/docarray
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind.py
More file actions
176 lines (147 loc) · 7.42 KB
/
find.py
File metadata and controls
176 lines (147 loc) · 7.42 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
from typing import Optional, Union, Tuple, Callable, TYPE_CHECKING
import numpy as np
from ....math import ndarray
from ....math.helper import top_k, minmax_normalize, update_rows_x_mat_best
if TYPE_CHECKING:
from ....typing import T, ArrayType
from .... import DocumentArray
class FindMixin:
"""A mixin that provides find functionality to DocumentArrays"""
def _find(
self: 'T',
query: 'ArrayType',
metric: Union[
str, Callable[['ArrayType', 'ArrayType'], 'np.ndarray']
] = 'cosine',
limit: Optional[Union[int, float]] = 20,
normalization: Optional[Tuple[float, float]] = None,
metric_name: Optional[str] = None,
batch_size: Optional[int] = None,
use_scipy: bool = False,
device: str = 'cpu',
num_worker: Optional[int] = 1,
**kwargs,
) -> Tuple['np.ndarray', 'np.ndarray']:
"""Returns approximate nearest neighbors given a batch of input queries.
:param query: the query embeddings to search
:param metric: the distance metric.
:param limit: the maximum number of matches, when not given defaults to 20.
:param normalization: a tuple [a, b] to be used with min-max normalization,
the min distance will be rescaled to `a`, the max distance will be rescaled to `b`
all values will be rescaled into range `[a, b]`.
:param metric_name: if provided, then match result will be marked with this string.
:param batch_size: if provided, then ``self.embeddings`` is loaded in batches, where each of them is at most ``batch_size``
elements. When `self.embeddings` is big, this can significantly speedup the computation.
:param use_scipy: if set, use ``scipy`` as the computation backend. Note, ``scipy`` does not support distance
on sparse matrix.
:param device: the computational device for ``.search()``, can be either `cpu` or `cuda`.
:param num_worker: the number of parallel workers. If not given, then the number of CPUs in the system will be used.
.. note::
This argument is only effective when ``batch_size`` is set.
:param kwargs: other kwargs.
:return: a list of DocumentArrays containing the closest Document objects for each of the queries in `query`.
"""
if batch_size is not None:
if batch_size <= 0:
raise ValueError(
f'`batch_size` must be larger than 0, receiving {batch_size}'
)
else:
batch_size = int(batch_size)
if callable(metric):
cdist = metric
elif isinstance(metric, str):
if use_scipy:
from scipy.spatial.distance import cdist as cdist
else:
from ....math.distance import cdist as _cdist
cdist = lambda *x: _cdist(*x, device=device)
else:
raise TypeError(
f'metric must be either string or a 2-arity function, received: {metric!r}'
)
metric_name = metric_name or (metric.__name__ if callable(metric) else metric)
if batch_size:
return self._find_nn_online(
query, cdist, limit, normalization, metric_name, batch_size, num_worker
)
else:
return self._find_nn(query, cdist, limit, normalization, metric_name)
def _find_nn(
self, query: 'ArrayType', cdist, limit, normalization, metric_name
) -> Tuple['np.ndarray', 'np.ndarray']:
"""
:param query: the query embeddings to search by.
:param cdist: the distance metric
:param limit: the maximum number of matches, when not given
all Documents in `darray` are considered as matches
:param normalization: a tuple [a, b] to be used with min-max normalization,
the min distance will be rescaled to `a`, the max distance will be rescaled to `b`
all values will be rescaled into range `[a, b]`.
:param metric_name: if provided, then match result will be marked with this string.
:return: distances and indices
"""
dists = cdist(query, self.embeddings, metric_name)
dist, idx = top_k(dists, min(limit, len(self)), descending=False)
if isinstance(normalization, (tuple, list)) and normalization is not None:
# normalization bound uses original distance not the top-k trimmed distance
min_d = np.min(dists, axis=-1, keepdims=True)
max_d = np.max(dists, axis=-1, keepdims=True)
dist = minmax_normalize(dist, normalization, (min_d, max_d))
return dist, idx
def _find_nn_online(
self,
query,
cdist,
limit,
normalization,
metric_name,
batch_size,
num_worker,
) -> Tuple['np.ndarray', 'np.ndarray']:
"""
:param query: the query embeddings to search by.
:param cdist: the distance metric
:param limit: the maximum number of matches, when not given
all Documents in `another` are considered as matches
:param normalization: a tuple [a, b] to be used with min-max normalization,
the min distance will be rescaled to `a`, the max distance will be rescaled to `b`
all values will be rescaled into range `[a, b]`.
:param batch_size: length of the chunks loaded into memory from darray.
:param metric_name: if provided, then match result will be marked with this string.
:param num_worker: the number of parallel workers. If not given, then the number of CPUs in the system will be used.
:return: distances and indices
"""
n_q, _ = ndarray.get_array_rows(query)
idx = 0
top_dists = np.inf * np.ones((n_q, limit))
top_inds = np.zeros((n_q, limit), dtype=int)
def _get_dist(da: 'DocumentArray'):
distances = cdist(query, da.embeddings, metric_name)
dists, inds = top_k(distances, limit, descending=False)
if isinstance(normalization, (tuple, list)) and normalization is not None:
dists = minmax_normalize(dists, normalization)
return dists, inds, len(da)
if num_worker is None or num_worker > 1:
# notice that all most all computations (regardless the framework) are conducted in C
# hence there is no worry on Python GIL and the backend can be safely put to `thread` to
# save unnecessary data passing. This in fact gives a huge boost on the performance.
_gen = self.map_batch(
_get_dist,
batch_size=batch_size,
backend='thread',
num_worker=num_worker,
)
else:
_gen = (_get_dist(b) for b in self.batch(batch_size=batch_size))
for (dists, inds, _bs) in _gen:
inds += idx
idx += _bs
top_dists, top_inds = update_rows_x_mat_best(
top_dists, top_inds, dists, inds, limit
)
# sort final the final `top_dists` and `top_inds` per row
permutation = np.argsort(top_dists, axis=1)
dist = np.take_along_axis(top_dists, permutation, axis=1)
idx = np.take_along_axis(top_inds, permutation, axis=1)
return dist, idx