fastembed-gpu 0.5.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fastembed/__init__.py +20 -0
- fastembed/common/__init__.py +3 -0
- fastembed/common/model_management.py +301 -0
- fastembed/common/onnx_model.py +132 -0
- fastembed/common/preprocessor_utils.py +82 -0
- fastembed/common/types.py +16 -0
- fastembed/common/utils.py +55 -0
- fastembed/embedding.py +24 -0
- fastembed/image/__init__.py +3 -0
- fastembed/image/image_embedding.py +97 -0
- fastembed/image/image_embedding_base.py +44 -0
- fastembed/image/onnx_embedding.py +211 -0
- fastembed/image/onnx_image_model.py +131 -0
- fastembed/image/transform/functional.py +150 -0
- fastembed/image/transform/operators.py +268 -0
- fastembed/late_interaction/__init__.py +5 -0
- fastembed/late_interaction/colbert.py +256 -0
- fastembed/late_interaction/jina_colbert.py +62 -0
- fastembed/late_interaction/late_interaction_embedding_base.py +62 -0
- fastembed/late_interaction/late_interaction_text_embedding.py +114 -0
- fastembed/parallel_processor.py +252 -0
- fastembed/rerank/cross_encoder/__init__.py +3 -0
- fastembed/rerank/cross_encoder/onnx_text_cross_encoder.py +224 -0
- fastembed/rerank/cross_encoder/onnx_text_model.py +150 -0
- fastembed/rerank/cross_encoder/text_cross_encoder.py +120 -0
- fastembed/rerank/cross_encoder/text_cross_encoder_base.py +58 -0
- fastembed/sparse/__init__.py +4 -0
- fastembed/sparse/bm25.py +347 -0
- fastembed/sparse/bm42.py +340 -0
- fastembed/sparse/sparse_embedding_base.py +83 -0
- fastembed/sparse/sparse_text_embedding.py +121 -0
- fastembed/sparse/splade_pp.py +180 -0
- fastembed/sparse/utils/tokenizer.py +120 -0
- fastembed/text/__init__.py +3 -0
- fastembed/text/clip_embedding.py +54 -0
- fastembed/text/e5_onnx_embedding.py +72 -0
- fastembed/text/onnx_embedding.py +333 -0
- fastembed/text/onnx_text_model.py +145 -0
- fastembed/text/pooled_embedding.py +92 -0
- fastembed/text/pooled_normalized_embedding.py +125 -0
- fastembed/text/text_embedding.py +107 -0
- fastembed/text/text_embedding_base.py +62 -0
- fastembed_gpu-0.5.1.dist-info/LICENSE +201 -0
- fastembed_gpu-0.5.1.dist-info/METADATA +262 -0
- fastembed_gpu-0.5.1.dist-info/NOTICE +14 -0
- fastembed_gpu-0.5.1.dist-info/RECORD +47 -0
- fastembed_gpu-0.5.1.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
from typing import Any, Iterable, Optional, Sequence, Type, Union
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from fastembed.common import OnnxProvider
|
|
6
|
+
from fastembed.common.onnx_model import OnnxOutputContext
|
|
7
|
+
from fastembed.common.utils import define_cache_dir, normalize
|
|
8
|
+
from fastembed.text.onnx_text_model import OnnxTextModel, TextEmbeddingWorker
|
|
9
|
+
from fastembed.text.text_embedding_base import TextEmbeddingBase
|
|
10
|
+
|
|
11
|
+
supported_onnx_models = [
|
|
12
|
+
{
|
|
13
|
+
"model": "BAAI/bge-base-en",
|
|
14
|
+
"dim": 768,
|
|
15
|
+
"description": "Text embeddings, Unimodal (text), English, 512 input tokens truncation, Prefixes for queries/documents: necessary, 2023 year.",
|
|
16
|
+
"license": "mit",
|
|
17
|
+
"size_in_GB": 0.42,
|
|
18
|
+
"sources": {
|
|
19
|
+
"hf": "Qdrant/fast-bge-base-en",
|
|
20
|
+
"url": "https://storage.googleapis.com/qdrant-fastembed/fast-bge-base-en.tar.gz",
|
|
21
|
+
},
|
|
22
|
+
"model_file": "model_optimized.onnx",
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
"model": "BAAI/bge-base-en-v1.5",
|
|
26
|
+
"dim": 768,
|
|
27
|
+
"description": "Text embeddings, Unimodal (text), English, 512 input tokens truncation, Prefixes for queries/documents: not so necessary, 2023 year.",
|
|
28
|
+
"license": "mit",
|
|
29
|
+
"size_in_GB": 0.21,
|
|
30
|
+
"sources": {
|
|
31
|
+
"url": "https://storage.googleapis.com/qdrant-fastembed/fast-bge-base-en-v1.5.tar.gz",
|
|
32
|
+
"hf": "qdrant/bge-base-en-v1.5-onnx-q",
|
|
33
|
+
},
|
|
34
|
+
"model_file": "model_optimized.onnx",
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
"model": "BAAI/bge-large-en-v1.5",
|
|
38
|
+
"dim": 1024,
|
|
39
|
+
"description": "Text embeddings, Unimodal (text), English, 512 input tokens truncation, Prefixes for queries/documents: not so necessary, 2023 year.",
|
|
40
|
+
"license": "mit",
|
|
41
|
+
"size_in_GB": 1.20,
|
|
42
|
+
"sources": {
|
|
43
|
+
"hf": "qdrant/bge-large-en-v1.5-onnx",
|
|
44
|
+
},
|
|
45
|
+
"model_file": "model.onnx",
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
"model": "BAAI/bge-small-en",
|
|
49
|
+
"dim": 384,
|
|
50
|
+
"description": "Text embeddings, Unimodal (text), English, 512 input tokens truncation, Prefixes for queries/documents: necessary, 2023 year.",
|
|
51
|
+
"license": "mit",
|
|
52
|
+
"size_in_GB": 0.13,
|
|
53
|
+
"sources": {
|
|
54
|
+
"hf": "Qdrant/bge-small-en",
|
|
55
|
+
"url": "https://storage.googleapis.com/qdrant-fastembed/BAAI-bge-small-en.tar.gz",
|
|
56
|
+
},
|
|
57
|
+
"model_file": "model_optimized.onnx",
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
"model": "BAAI/bge-small-en-v1.5",
|
|
61
|
+
"dim": 384,
|
|
62
|
+
"description": "Text embeddings, Unimodal (text), English, 512 input tokens truncation, Prefixes for queries/documents: not so necessary, 2023 year.",
|
|
63
|
+
"license": "mit",
|
|
64
|
+
"size_in_GB": 0.067,
|
|
65
|
+
"sources": {
|
|
66
|
+
"hf": "qdrant/bge-small-en-v1.5-onnx-q",
|
|
67
|
+
},
|
|
68
|
+
"model_file": "model_optimized.onnx",
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
"model": "BAAI/bge-small-zh-v1.5",
|
|
72
|
+
"dim": 512,
|
|
73
|
+
"description": "Text embeddings, Unimodal (text), Chinese, 512 input tokens truncation, Prefixes for queries/documents: not so necessary, 2023 year.",
|
|
74
|
+
"license": "mit",
|
|
75
|
+
"size_in_GB": 0.09,
|
|
76
|
+
"sources": {
|
|
77
|
+
"hf": "Qdrant/bge-small-zh-v1.5",
|
|
78
|
+
"url": "https://storage.googleapis.com/qdrant-fastembed/fast-bge-small-zh-v1.5.tar.gz",
|
|
79
|
+
},
|
|
80
|
+
"model_file": "model_optimized.onnx",
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
"model": "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
|
|
84
|
+
"dim": 384,
|
|
85
|
+
"description": "Text embeddings, Unimodal (text), Multilingual (~50 languages), 512 input tokens truncation, Prefixes for queries/documents: not necessary, 2019 year.",
|
|
86
|
+
"license": "apache-2.0",
|
|
87
|
+
"size_in_GB": 0.22,
|
|
88
|
+
"sources": {
|
|
89
|
+
"hf": "qdrant/paraphrase-multilingual-MiniLM-L12-v2-onnx-Q",
|
|
90
|
+
},
|
|
91
|
+
"model_file": "model_optimized.onnx",
|
|
92
|
+
},
|
|
93
|
+
{
|
|
94
|
+
"model": "thenlper/gte-large",
|
|
95
|
+
"dim": 1024,
|
|
96
|
+
"description": "Text embeddings, Unimodal (text), English, 512 input tokens truncation, Prefixes for queries/documents: not necessary, 2023 year.",
|
|
97
|
+
"license": "mit",
|
|
98
|
+
"size_in_GB": 1.20,
|
|
99
|
+
"sources": {
|
|
100
|
+
"hf": "qdrant/gte-large-onnx",
|
|
101
|
+
},
|
|
102
|
+
"model_file": "model.onnx",
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
"model": "mixedbread-ai/mxbai-embed-large-v1",
|
|
106
|
+
"dim": 1024,
|
|
107
|
+
"description": "Text embeddings, Unimodal (text), English, 512 input tokens truncation, Prefixes for queries/documents: necessary, 2024 year.",
|
|
108
|
+
"license": "apache-2.0",
|
|
109
|
+
"size_in_GB": 0.64,
|
|
110
|
+
"sources": {
|
|
111
|
+
"hf": "mixedbread-ai/mxbai-embed-large-v1",
|
|
112
|
+
},
|
|
113
|
+
"model_file": "onnx/model.onnx",
|
|
114
|
+
},
|
|
115
|
+
{
|
|
116
|
+
"model": "snowflake/snowflake-arctic-embed-xs",
|
|
117
|
+
"dim": 384,
|
|
118
|
+
"description": "Text embeddings, Unimodal (text), English, 512 input tokens truncation, Prefixes for queries/documents: necessary, 2024 year.",
|
|
119
|
+
"license": "apache-2.0",
|
|
120
|
+
"size_in_GB": 0.09,
|
|
121
|
+
"sources": {
|
|
122
|
+
"hf": "snowflake/snowflake-arctic-embed-xs",
|
|
123
|
+
},
|
|
124
|
+
"model_file": "onnx/model.onnx",
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
"model": "snowflake/snowflake-arctic-embed-s",
|
|
128
|
+
"dim": 384,
|
|
129
|
+
"description": "Text embeddings, Unimodal (text), English, 512 input tokens truncation, Prefixes for queries/documents: necessary, 2024 year.",
|
|
130
|
+
"license": "apache-2.0",
|
|
131
|
+
"size_in_GB": 0.13,
|
|
132
|
+
"sources": {
|
|
133
|
+
"hf": "snowflake/snowflake-arctic-embed-s",
|
|
134
|
+
},
|
|
135
|
+
"model_file": "onnx/model.onnx",
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
"model": "snowflake/snowflake-arctic-embed-m",
|
|
139
|
+
"dim": 768,
|
|
140
|
+
"description": "Text embeddings, Unimodal (text), English, 512 input tokens truncation, Prefixes for queries/documents: necessary, 2024 year.",
|
|
141
|
+
"license": "apache-2.0",
|
|
142
|
+
"size_in_GB": 0.43,
|
|
143
|
+
"sources": {
|
|
144
|
+
"hf": "Snowflake/snowflake-arctic-embed-m",
|
|
145
|
+
},
|
|
146
|
+
"model_file": "onnx/model.onnx",
|
|
147
|
+
},
|
|
148
|
+
{
|
|
149
|
+
"model": "snowflake/snowflake-arctic-embed-m-long",
|
|
150
|
+
"dim": 768,
|
|
151
|
+
"description": "Text embeddings, Unimodal (text), English, 2048 input tokens truncation, Prefixes for queries/documents: necessary, 2024 year.",
|
|
152
|
+
"license": "apache-2.0",
|
|
153
|
+
"size_in_GB": 0.54,
|
|
154
|
+
"sources": {
|
|
155
|
+
"hf": "snowflake/snowflake-arctic-embed-m-long",
|
|
156
|
+
},
|
|
157
|
+
"model_file": "onnx/model.onnx",
|
|
158
|
+
},
|
|
159
|
+
{
|
|
160
|
+
"model": "snowflake/snowflake-arctic-embed-l",
|
|
161
|
+
"dim": 1024,
|
|
162
|
+
"description": "Text embeddings, Unimodal (text), English, 512 input tokens truncation, Prefixes for queries/documents: necessary, 2024 year.",
|
|
163
|
+
"license": "apache-2.0",
|
|
164
|
+
"size_in_GB": 1.02,
|
|
165
|
+
"sources": {
|
|
166
|
+
"hf": "snowflake/snowflake-arctic-embed-l",
|
|
167
|
+
},
|
|
168
|
+
"model_file": "onnx/model.onnx",
|
|
169
|
+
},
|
|
170
|
+
{
|
|
171
|
+
"model": "jinaai/jina-clip-v1",
|
|
172
|
+
"dim": 768,
|
|
173
|
+
"description": "Text embeddings, Multimodal (text&image), English, Prefixes for queries/documents: not necessary, 2024 year",
|
|
174
|
+
"license": "apache-2.0",
|
|
175
|
+
"size_in_GB": 0.55,
|
|
176
|
+
"sources": {
|
|
177
|
+
"hf": "jinaai/jina-clip-v1",
|
|
178
|
+
},
|
|
179
|
+
"model_file": "onnx/text_model.onnx",
|
|
180
|
+
},
|
|
181
|
+
]
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class OnnxTextEmbedding(TextEmbeddingBase, OnnxTextModel[np.ndarray]):
|
|
185
|
+
"""Implementation of the Flag Embedding model."""
|
|
186
|
+
|
|
187
|
+
@classmethod
|
|
188
|
+
def list_supported_models(cls) -> list[dict[str, Any]]:
|
|
189
|
+
"""
|
|
190
|
+
Lists the supported models.
|
|
191
|
+
|
|
192
|
+
Returns:
|
|
193
|
+
list[dict[str, Any]]: A list of dictionaries containing the model information.
|
|
194
|
+
"""
|
|
195
|
+
return supported_onnx_models
|
|
196
|
+
|
|
197
|
+
def __init__(
|
|
198
|
+
self,
|
|
199
|
+
model_name: str = "BAAI/bge-small-en-v1.5",
|
|
200
|
+
cache_dir: Optional[str] = None,
|
|
201
|
+
threads: Optional[int] = None,
|
|
202
|
+
providers: Optional[Sequence[OnnxProvider]] = None,
|
|
203
|
+
cuda: bool = False,
|
|
204
|
+
device_ids: Optional[list[int]] = None,
|
|
205
|
+
lazy_load: bool = False,
|
|
206
|
+
device_id: Optional[int] = None,
|
|
207
|
+
**kwargs,
|
|
208
|
+
):
|
|
209
|
+
"""
|
|
210
|
+
Args:
|
|
211
|
+
model_name (str): The name of the model to use.
|
|
212
|
+
cache_dir (str, optional): The path to the cache directory.
|
|
213
|
+
Can be set using the `FASTEMBED_CACHE_PATH` env variable.
|
|
214
|
+
Defaults to `fastembed_cache` in the system's temp directory.
|
|
215
|
+
threads (int, optional): The number of threads single onnxruntime session can use. Defaults to None.
|
|
216
|
+
providers (Optional[Sequence[OnnxProvider]], optional): The list of onnxruntime providers to use.
|
|
217
|
+
Mutually exclusive with the `cuda` and `device_ids` arguments. Defaults to None.
|
|
218
|
+
cuda (bool, optional): Whether to use cuda for inference. Mutually exclusive with `providers`
|
|
219
|
+
Defaults to False.
|
|
220
|
+
device_ids (Optional[list[int]], optional): The list of device ids to use for data parallel processing in
|
|
221
|
+
workers. Should be used with `cuda=True`, mutually exclusive with `providers`. Defaults to None.
|
|
222
|
+
lazy_load (bool, optional): Whether to load the model during class initialization or on demand.
|
|
223
|
+
Should be set to True when using multiple-gpu and parallel encoding. Defaults to False.
|
|
224
|
+
device_id (Optional[int], optional): The device id to use for loading the model in the worker process.
|
|
225
|
+
|
|
226
|
+
Raises:
|
|
227
|
+
ValueError: If the model_name is not in the format <org>/<model> e.g. BAAI/bge-base-en.
|
|
228
|
+
"""
|
|
229
|
+
super().__init__(model_name, cache_dir, threads, **kwargs)
|
|
230
|
+
self.providers = providers
|
|
231
|
+
self.lazy_load = lazy_load
|
|
232
|
+
|
|
233
|
+
# List of device ids, that can be used for data parallel processing in workers
|
|
234
|
+
self.device_ids = device_ids
|
|
235
|
+
self.cuda = cuda
|
|
236
|
+
|
|
237
|
+
# This device_id will be used if we need to load model in current process
|
|
238
|
+
if device_id is not None:
|
|
239
|
+
self.device_id = device_id
|
|
240
|
+
elif self.device_ids is not None:
|
|
241
|
+
self.device_id = self.device_ids[0]
|
|
242
|
+
else:
|
|
243
|
+
self.device_id = None
|
|
244
|
+
|
|
245
|
+
self.model_description = self._get_model_description(model_name)
|
|
246
|
+
self.cache_dir = define_cache_dir(cache_dir)
|
|
247
|
+
self._model_dir = self.download_model(
|
|
248
|
+
self.model_description, self.cache_dir, local_files_only=self._local_files_only
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
if not self.lazy_load:
|
|
252
|
+
self.load_onnx_model()
|
|
253
|
+
|
|
254
|
+
def embed(
|
|
255
|
+
self,
|
|
256
|
+
documents: Union[str, Iterable[str]],
|
|
257
|
+
batch_size: int = 256,
|
|
258
|
+
parallel: Optional[int] = None,
|
|
259
|
+
**kwargs,
|
|
260
|
+
) -> Iterable[np.ndarray]:
|
|
261
|
+
"""
|
|
262
|
+
Encode a list of documents into list of embeddings.
|
|
263
|
+
We use mean pooling with attention so that the model can handle variable-length inputs.
|
|
264
|
+
|
|
265
|
+
Args:
|
|
266
|
+
documents: Iterator of documents or single document to embed
|
|
267
|
+
batch_size: Batch size for encoding -- higher values will use more memory, but be faster
|
|
268
|
+
parallel:
|
|
269
|
+
If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets.
|
|
270
|
+
If 0, use all available cores.
|
|
271
|
+
If None, don't use data-parallel processing, use default onnxruntime threading instead.
|
|
272
|
+
|
|
273
|
+
Returns:
|
|
274
|
+
List of embeddings, one per document
|
|
275
|
+
"""
|
|
276
|
+
yield from self._embed_documents(
|
|
277
|
+
model_name=self.model_name,
|
|
278
|
+
cache_dir=str(self.cache_dir),
|
|
279
|
+
documents=documents,
|
|
280
|
+
batch_size=batch_size,
|
|
281
|
+
parallel=parallel,
|
|
282
|
+
providers=self.providers,
|
|
283
|
+
cuda=self.cuda,
|
|
284
|
+
device_ids=self.device_ids,
|
|
285
|
+
**kwargs,
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
@classmethod
|
|
289
|
+
def _get_worker_class(cls) -> Type["TextEmbeddingWorker"]:
|
|
290
|
+
return OnnxTextEmbeddingWorker
|
|
291
|
+
|
|
292
|
+
def _preprocess_onnx_input(
|
|
293
|
+
self, onnx_input: dict[str, np.ndarray], **kwargs
|
|
294
|
+
) -> dict[str, np.ndarray]:
|
|
295
|
+
"""
|
|
296
|
+
Preprocess the onnx input.
|
|
297
|
+
"""
|
|
298
|
+
return onnx_input
|
|
299
|
+
|
|
300
|
+
def _post_process_onnx_output(self, output: OnnxOutputContext) -> Iterable[np.ndarray]:
|
|
301
|
+
embeddings = output.model_output
|
|
302
|
+
if embeddings.ndim == 3: # (batch_size, seq_len, embedding_dim)
|
|
303
|
+
processed_embeddings = embeddings[:, 0]
|
|
304
|
+
elif embeddings.ndim == 2: # (batch_size, embedding_dim)
|
|
305
|
+
processed_embeddings = embeddings
|
|
306
|
+
else:
|
|
307
|
+
raise ValueError(f"Unsupported embedding shape: {embeddings.shape}")
|
|
308
|
+
return normalize(processed_embeddings).astype(np.float32)
|
|
309
|
+
|
|
310
|
+
def load_onnx_model(self) -> None:
|
|
311
|
+
self._load_onnx_model(
|
|
312
|
+
model_dir=self._model_dir,
|
|
313
|
+
model_file=self.model_description["model_file"],
|
|
314
|
+
threads=self.threads,
|
|
315
|
+
providers=self.providers,
|
|
316
|
+
cuda=self.cuda,
|
|
317
|
+
device_id=self.device_id,
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
class OnnxTextEmbeddingWorker(TextEmbeddingWorker):
|
|
322
|
+
def init_embedding(
|
|
323
|
+
self,
|
|
324
|
+
model_name: str,
|
|
325
|
+
cache_dir: str,
|
|
326
|
+
**kwargs,
|
|
327
|
+
) -> OnnxTextEmbedding:
|
|
328
|
+
return OnnxTextEmbedding(
|
|
329
|
+
model_name=model_name,
|
|
330
|
+
cache_dir=cache_dir,
|
|
331
|
+
threads=1,
|
|
332
|
+
**kwargs,
|
|
333
|
+
)
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from multiprocessing import get_all_start_methods
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any, Iterable, Optional, Sequence, Type, Union
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
from tokenizers import Encoding
|
|
8
|
+
|
|
9
|
+
from fastembed.common import OnnxProvider
|
|
10
|
+
from fastembed.common.onnx_model import EmbeddingWorker, OnnxModel, OnnxOutputContext, T
|
|
11
|
+
from fastembed.common.preprocessor_utils import load_tokenizer
|
|
12
|
+
from fastembed.common.utils import iter_batch
|
|
13
|
+
from fastembed.parallel_processor import ParallelWorkerPool
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class OnnxTextModel(OnnxModel[T]):
|
|
17
|
+
ONNX_OUTPUT_NAMES: Optional[list[str]] = None
|
|
18
|
+
|
|
19
|
+
@classmethod
|
|
20
|
+
def _get_worker_class(cls) -> Type["TextEmbeddingWorker"]:
|
|
21
|
+
raise NotImplementedError("Subclasses must implement this method")
|
|
22
|
+
|
|
23
|
+
def _post_process_onnx_output(self, output: OnnxOutputContext) -> Iterable[T]:
|
|
24
|
+
raise NotImplementedError("Subclasses must implement this method")
|
|
25
|
+
|
|
26
|
+
def __init__(self) -> None:
|
|
27
|
+
super().__init__()
|
|
28
|
+
self.tokenizer = None
|
|
29
|
+
self.special_token_to_id = {}
|
|
30
|
+
|
|
31
|
+
def _preprocess_onnx_input(
|
|
32
|
+
self, onnx_input: dict[str, np.ndarray], **kwargs
|
|
33
|
+
) -> dict[str, np.ndarray]:
|
|
34
|
+
"""
|
|
35
|
+
Preprocess the onnx input.
|
|
36
|
+
"""
|
|
37
|
+
return onnx_input
|
|
38
|
+
|
|
39
|
+
def _load_onnx_model(
|
|
40
|
+
self,
|
|
41
|
+
model_dir: Path,
|
|
42
|
+
model_file: str,
|
|
43
|
+
threads: Optional[int],
|
|
44
|
+
providers: Optional[Sequence[OnnxProvider]] = None,
|
|
45
|
+
cuda: bool = False,
|
|
46
|
+
device_id: Optional[int] = None,
|
|
47
|
+
) -> None:
|
|
48
|
+
super()._load_onnx_model(
|
|
49
|
+
model_dir=model_dir,
|
|
50
|
+
model_file=model_file,
|
|
51
|
+
threads=threads,
|
|
52
|
+
providers=providers,
|
|
53
|
+
cuda=cuda,
|
|
54
|
+
device_id=device_id,
|
|
55
|
+
)
|
|
56
|
+
self.tokenizer, self.special_token_to_id = load_tokenizer(model_dir=model_dir)
|
|
57
|
+
|
|
58
|
+
def load_onnx_model(self) -> None:
|
|
59
|
+
raise NotImplementedError("Subclasses must implement this method")
|
|
60
|
+
|
|
61
|
+
def tokenize(self, documents: list[str], **kwargs) -> list[Encoding]:
|
|
62
|
+
return self.tokenizer.encode_batch(documents)
|
|
63
|
+
|
|
64
|
+
def onnx_embed(
|
|
65
|
+
self,
|
|
66
|
+
documents: list[str],
|
|
67
|
+
**kwargs,
|
|
68
|
+
) -> OnnxOutputContext:
|
|
69
|
+
encoded = self.tokenize(documents, **kwargs)
|
|
70
|
+
input_ids = np.array([e.ids for e in encoded])
|
|
71
|
+
attention_mask = np.array([e.attention_mask for e in encoded])
|
|
72
|
+
input_names = {node.name for node in self.model.get_inputs()}
|
|
73
|
+
onnx_input = {
|
|
74
|
+
"input_ids": np.array(input_ids, dtype=np.int64),
|
|
75
|
+
}
|
|
76
|
+
if "attention_mask" in input_names:
|
|
77
|
+
onnx_input["attention_mask"] = np.array(attention_mask, dtype=np.int64)
|
|
78
|
+
if "token_type_ids" in input_names:
|
|
79
|
+
onnx_input["token_type_ids"] = np.array(
|
|
80
|
+
[np.zeros(len(e), dtype=np.int64) for e in input_ids], dtype=np.int64
|
|
81
|
+
)
|
|
82
|
+
onnx_input = self._preprocess_onnx_input(onnx_input, **kwargs)
|
|
83
|
+
|
|
84
|
+
model_output = self.model.run(self.ONNX_OUTPUT_NAMES, onnx_input)
|
|
85
|
+
return OnnxOutputContext(
|
|
86
|
+
model_output=model_output[0],
|
|
87
|
+
attention_mask=onnx_input.get("attention_mask", attention_mask),
|
|
88
|
+
input_ids=onnx_input.get("input_ids", input_ids),
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
def _embed_documents(
|
|
92
|
+
self,
|
|
93
|
+
model_name: str,
|
|
94
|
+
cache_dir: str,
|
|
95
|
+
documents: Union[str, Iterable[str]],
|
|
96
|
+
batch_size: int = 256,
|
|
97
|
+
parallel: Optional[int] = None,
|
|
98
|
+
providers: Optional[Sequence[OnnxProvider]] = None,
|
|
99
|
+
cuda: bool = False,
|
|
100
|
+
device_ids: Optional[list[int]] = None,
|
|
101
|
+
**kwargs,
|
|
102
|
+
) -> Iterable[T]:
|
|
103
|
+
is_small = False
|
|
104
|
+
|
|
105
|
+
if isinstance(documents, str):
|
|
106
|
+
documents = [documents]
|
|
107
|
+
is_small = True
|
|
108
|
+
|
|
109
|
+
if isinstance(documents, list):
|
|
110
|
+
if len(documents) < batch_size:
|
|
111
|
+
is_small = True
|
|
112
|
+
|
|
113
|
+
if parallel is None or is_small:
|
|
114
|
+
if not hasattr(self, "model") or self.model is None:
|
|
115
|
+
self.load_onnx_model()
|
|
116
|
+
for batch in iter_batch(documents, batch_size):
|
|
117
|
+
yield from self._post_process_onnx_output(self.onnx_embed(batch))
|
|
118
|
+
else:
|
|
119
|
+
if parallel == 0:
|
|
120
|
+
parallel = os.cpu_count()
|
|
121
|
+
|
|
122
|
+
start_method = "forkserver" if "forkserver" in get_all_start_methods() else "spawn"
|
|
123
|
+
params = {
|
|
124
|
+
"model_name": model_name,
|
|
125
|
+
"cache_dir": cache_dir,
|
|
126
|
+
"providers": providers,
|
|
127
|
+
**kwargs,
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
pool = ParallelWorkerPool(
|
|
131
|
+
num_workers=parallel or 1,
|
|
132
|
+
worker=self._get_worker_class(),
|
|
133
|
+
cuda=cuda,
|
|
134
|
+
device_ids=device_ids,
|
|
135
|
+
start_method=start_method,
|
|
136
|
+
)
|
|
137
|
+
for batch in pool.ordered_map(iter_batch(documents, batch_size), **params):
|
|
138
|
+
yield from self._post_process_onnx_output(batch)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class TextEmbeddingWorker(EmbeddingWorker):
|
|
142
|
+
def process(self, items: Iterable[tuple[int, Any]]) -> Iterable[tuple[int, Any]]:
|
|
143
|
+
for idx, batch in items:
|
|
144
|
+
onnx_output = self.model.onnx_embed(batch)
|
|
145
|
+
yield idx, onnx_output
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
from typing import Any, Iterable, Type
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from fastembed.common.onnx_model import OnnxOutputContext
|
|
6
|
+
from fastembed.text.onnx_embedding import OnnxTextEmbedding, OnnxTextEmbeddingWorker
|
|
7
|
+
from fastembed.text.onnx_text_model import TextEmbeddingWorker
|
|
8
|
+
|
|
9
|
+
supported_pooled_models = [
|
|
10
|
+
{
|
|
11
|
+
"model": "nomic-ai/nomic-embed-text-v1.5",
|
|
12
|
+
"dim": 768,
|
|
13
|
+
"description": "Text embeddings, Multimodal (text, image), English, 8192 input tokens truncation, Prefixes for queries/documents: necessary, 2024 year.",
|
|
14
|
+
"license": "apache-2.0",
|
|
15
|
+
"size_in_GB": 0.52,
|
|
16
|
+
"sources": {
|
|
17
|
+
"hf": "nomic-ai/nomic-embed-text-v1.5",
|
|
18
|
+
},
|
|
19
|
+
"model_file": "onnx/model.onnx",
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
"model": "nomic-ai/nomic-embed-text-v1.5-Q",
|
|
23
|
+
"dim": 768,
|
|
24
|
+
"description": "Text embeddings, Multimodal (text, image), English, 8192 input tokens truncation, Prefixes for queries/documents: necessary, 2024 year.",
|
|
25
|
+
"license": "apache-2.0",
|
|
26
|
+
"size_in_GB": 0.13,
|
|
27
|
+
"sources": {
|
|
28
|
+
"hf": "nomic-ai/nomic-embed-text-v1.5",
|
|
29
|
+
},
|
|
30
|
+
"model_file": "onnx/model_quantized.onnx",
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
"model": "nomic-ai/nomic-embed-text-v1",
|
|
34
|
+
"dim": 768,
|
|
35
|
+
"description": "Text embeddings, Multimodal (text, image), English, 8192 input tokens truncation, Prefixes for queries/documents: necessary, 2024 year.",
|
|
36
|
+
"license": "apache-2.0",
|
|
37
|
+
"size_in_GB": 0.52,
|
|
38
|
+
"sources": {
|
|
39
|
+
"hf": "nomic-ai/nomic-embed-text-v1",
|
|
40
|
+
},
|
|
41
|
+
"model_file": "onnx/model.onnx",
|
|
42
|
+
},
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class PooledEmbedding(OnnxTextEmbedding):
|
|
47
|
+
@classmethod
|
|
48
|
+
def _get_worker_class(cls) -> Type[TextEmbeddingWorker]:
|
|
49
|
+
return PooledEmbeddingWorker
|
|
50
|
+
|
|
51
|
+
@classmethod
|
|
52
|
+
def mean_pooling(cls, model_output: np.ndarray, attention_mask: np.ndarray) -> np.ndarray:
|
|
53
|
+
token_embeddings = model_output
|
|
54
|
+
input_mask_expanded = np.expand_dims(attention_mask, axis=-1)
|
|
55
|
+
input_mask_expanded = np.tile(input_mask_expanded, (1, 1, token_embeddings.shape[-1]))
|
|
56
|
+
input_mask_expanded = input_mask_expanded.astype(float)
|
|
57
|
+
sum_embeddings = np.sum(token_embeddings * input_mask_expanded, axis=1)
|
|
58
|
+
sum_mask = np.sum(input_mask_expanded, axis=1)
|
|
59
|
+
pooled_embeddings = sum_embeddings / np.maximum(sum_mask, 1e-9)
|
|
60
|
+
return pooled_embeddings
|
|
61
|
+
|
|
62
|
+
@classmethod
|
|
63
|
+
def list_supported_models(cls) -> list[dict[str, Any]]:
|
|
64
|
+
"""Lists the supported models.
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
list[dict[str, Any]]: A list of dictionaries containing the model information.
|
|
68
|
+
"""
|
|
69
|
+
return supported_pooled_models
|
|
70
|
+
|
|
71
|
+
def _post_process_onnx_output(self, output: OnnxOutputContext) -> Iterable[np.ndarray]:
|
|
72
|
+
if output.attention_mask is None:
|
|
73
|
+
raise ValueError("attention_mask must be provided for document post-processing")
|
|
74
|
+
|
|
75
|
+
embeddings = output.model_output
|
|
76
|
+
attn_mask = output.attention_mask
|
|
77
|
+
return self.mean_pooling(embeddings, attn_mask).astype(np.float32)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class PooledEmbeddingWorker(OnnxTextEmbeddingWorker):
|
|
81
|
+
def init_embedding(
|
|
82
|
+
self,
|
|
83
|
+
model_name: str,
|
|
84
|
+
cache_dir: str,
|
|
85
|
+
**kwargs,
|
|
86
|
+
) -> OnnxTextEmbedding:
|
|
87
|
+
return PooledEmbedding(
|
|
88
|
+
model_name=model_name,
|
|
89
|
+
cache_dir=cache_dir,
|
|
90
|
+
threads=1,
|
|
91
|
+
**kwargs,
|
|
92
|
+
)
|