-
Notifications
You must be signed in to change notification settings - Fork 244
Expand file tree
/
Copy pathfind.py
More file actions
287 lines (242 loc) · 9.5 KB
/
Copy pathfind.py
File metadata and controls
287 lines (242 loc) · 9.5 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
__all__ = ['find', 'find_batched']
from typing import Any, Dict, List, NamedTuple, Optional, Type, Union, cast
from typing_inspect import is_union_type
from docarray.array.abstract_array import AnyDocArray
from docarray.array.array.array import DocArray
from docarray.array.stacked.array_stacked import DocArrayStacked
from docarray.base_doc import BaseDoc
from docarray.helper import _get_field_type_by_access_path
from docarray.typing import AnyTensor
from docarray.typing.tensor.abstract_tensor import AbstractTensor
class FindResult(NamedTuple):
documents: DocArray
scores: AnyTensor
class _FindResult(NamedTuple):
documents: Union[DocArray, List[Dict[str, Any]]]
scores: AnyTensor
def find(
index: AnyDocArray,
query: Union[AnyTensor, BaseDoc],
embedding_field: str = 'embedding',
metric: str = 'cosine_sim',
limit: int = 10,
device: Optional[str] = None,
descending: Optional[bool] = None,
) -> FindResult:
"""
Find the closest Documents in the index to the query.
Supports PyTorch and NumPy embeddings.
!!! note
This is a simple implementation of exact search. If you need to do advance
search using approximate nearest neighbours search or hybrid search or
multi vector search please take a look at the [BaseDoc][docarray.base_doc.doc.BaseDoc]
---
```python
from docarray import DocArray, BaseDoc
from docarray.typing import TorchTensor
from docarray.utils.find import find
import torch
class MyDocument(BaseDoc):
embedding: TorchTensor
index = DocArray[MyDocument](
[MyDocument(embedding=torch.rand(128)) for _ in range(100)]
)
# use Document as query
query = MyDocument(embedding=torch.rand(128))
top_matches, scores = find(
index=index,
query=query,
embedding_field='embedding',
metric='cosine_sim',
)
# use tensor as query
query = torch.rand(128)
top_matches, scores = find(
index=index,
query=query,
embedding_field='embedding',
metric='cosine_sim',
)
```
---
:param index: the index of Documents to search in
:param query: the query to search for
:param embedding_field: the tensor-like field in the index to use
for the similarity computation
:param metric: the distance metric to use for the similarity computation.
Can be one of the following strings:
'cosine_sim' for cosine similarity, 'euclidean_dist' for euclidean distance,
'sqeuclidean_dist' for squared euclidean distance
:param limit: return the top `limit` results
:param device: the computational device to use,
can be either `cpu` or a `cuda` device.
:param descending: sort the results in descending order.
Per default, this is chosen based on the `metric` argument.
:return: A named tuple of the form (DocArray, AnyTensor),
where the first element contains the closes matches for the query,
and the second element contains the corresponding scores.
"""
query = _extract_embedding_single(query, embedding_field)
return find_batched(
index=index,
query=query,
embedding_field=embedding_field,
metric=metric,
limit=limit,
device=device,
descending=descending,
)[0]
def find_batched(
index: AnyDocArray,
query: Union[AnyTensor, DocArray],
embedding_field: str = 'embedding',
metric: str = 'cosine_sim',
limit: int = 10,
device: Optional[str] = None,
descending: Optional[bool] = None,
) -> List[FindResult]:
"""
Find the closest Documents in the index to the queries.
Supports PyTorch and NumPy embeddings.
!!! note
This is a simple implementation of exact search. If you need to do advance
search using approximate nearest neighbours search or hybrid search or
multi vector search please take a look at the [BaseDoc][docarray.base_doc.doc.BaseDoc]
---
```python
# from docarray import DocArray, BaseDoc
# from docarray.typing import TorchTensor
# from docarray.utils.find import find
# import torch
#
#
# class MyDocument(BaseDoc):
# embedding: TorchTensor
#
#
# index = DocArray[MyDocument](
# [MyDocument(embedding=torch.rand(128)) for _ in range(100)]
# )
#
# # use DocArray as query
# query = DocArray[MyDocument]([MyDocument(embedding=torch.rand(128)) for _ in range(3)])
# results = find(
# index=index,
# query=query,
# embedding_field='embedding',
# metric='cosine_sim',
# )
# top_matches, scores = results[0]
#
# # use tensor as query
# query = torch.rand(3, 128)
# results, scores = find(
# index=index,
# query=query,
# embedding_field='embedding',
# metric='cosine_sim',
# )
# top_matches, scores = results[0]
```
---
:param index: the index of Documents to search in
:param query: the query to search for
:param embedding_field: the tensor-like field in the index to use
for the similarity computation
:param metric: the distance metric to use for the similarity computation.
Can be one of the following strings:
'cosine_sim' for cosine similarity, 'euclidean_dist' for euclidean distance,
'sqeuclidean_dist' for squared euclidean distance
:param limit: return the top `limit` results
:param device: the computational device to use,
can be either `cpu` or a `cuda` device.
:param descending: sort the results in descending order.
Per default, this is chosen based on the `metric` argument.
:return: a list of named tuples of the form (DocArray, AnyTensor),
where the first element contains the closes matches for each query,
and the second element contains the corresponding scores.
"""
if descending is None:
descending = metric.endswith('_sim') # similarity metrics are descending
embedding_type = _da_attr_type(index, embedding_field)
comp_backend = embedding_type.get_comp_backend()
# extract embeddings from query and index
index_embeddings = _extract_embeddings(index, embedding_field, embedding_type)
query_embeddings = _extract_embeddings(query, embedding_field, embedding_type)
# compute distances and return top results
metric_fn = getattr(comp_backend.Metrics, metric)
dists = metric_fn(query_embeddings, index_embeddings, device=device)
top_scores, top_indices = comp_backend.Retrieval.top_k(
dists, k=limit, device=device, descending=descending
)
results = []
for indices_per_query, scores_per_query in zip(top_indices, top_scores):
docs_per_query: DocArray = DocArray([])
for idx in indices_per_query: # workaround until #930 is fixed
docs_per_query.append(index[idx])
docs_per_query = DocArray(docs_per_query)
results.append(FindResult(scores=scores_per_query, documents=docs_per_query))
return results
def _extract_embedding_single(
data: Union[DocArray, BaseDoc, AnyTensor],
embedding_field: str,
) -> AnyTensor:
"""Extract the embeddings from a single query,
and return it in a batched representation.
:param data: the data
:param embedding_field: the embedding field
:param embedding_type: type of the embedding: torch.Tensor, numpy.ndarray etc.
:return: the embeddings
"""
if isinstance(data, BaseDoc):
emb = next(AnyDocArray._traverse(data, embedding_field))
else: # treat data as tensor
emb = data
if len(emb.shape) == 1:
# all currently supported frameworks provide `.reshape()`. Onc this is not true
# anymore, we need to add a `.reshape()` method to the computational backend
emb = emb.reshape(1, -1)
return emb
def _extract_embeddings(
data: Union[AnyDocArray, BaseDoc, AnyTensor],
embedding_field: str,
embedding_type: Type,
) -> AnyTensor:
"""Extract the embeddings from the data.
:param data: the data
:param embedding_field: the embedding field
:param embedding_type: type of the embedding: torch.Tensor, numpy.ndarray etc.
:return: the embeddings
"""
emb: AnyTensor
if isinstance(data, DocArray):
emb_list = list(AnyDocArray._traverse(data, embedding_field))
emb = embedding_type._docarray_stack(emb_list)
elif isinstance(data, (DocArrayStacked, BaseDoc)):
emb = next(AnyDocArray._traverse(data, embedding_field))
else: # treat data as tensor
emb = cast(AnyTensor, data)
if len(emb.shape) == 1:
emb = emb.get_comp_backend().reshape(array=emb, shape=(1, -1))
return emb
def _da_attr_type(da: AnyDocArray, access_path: str) -> Type[AnyTensor]:
"""Get the type of the attribute according to the Document type
(schema) of the DocArray.
:param da: the DocArray
:param access_path: the "__"-separated access path
:return: the type of the attribute
"""
field_type: Optional[Type] = _get_field_type_by_access_path(
da.document_type, access_path
)
if field_type is None:
raise ValueError(f"Access path is not valid: {access_path}")
if is_union_type(field_type):
# determine type based on the fist element
field_type = type(next(AnyDocArray._traverse(da[0], access_path)))
if not issubclass(field_type, AbstractTensor):
raise ValueError(
f'attribute {access_path} is not a tensor-like type, '
f'but {field_type.__class__.__name__}'
)
return cast(Type[AnyTensor], field_type)