davidtran999 commited on
Commit
81b824e
·
verified ·
1 Parent(s): 258d5e6

Upload backend/venv/lib/python3.10/site-packages/sentence_transformers/util.py with huggingface_hub

Browse files
backend/venv/lib/python3.10/site-packages/sentence_transformers/util.py ADDED
@@ -0,0 +1,1445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import functools
4
+ import heapq
5
+ import importlib
6
+ import logging
7
+ import os
8
+ import queue
9
+ import random
10
+ import sys
11
+ from contextlib import contextmanager
12
+ from importlib.metadata import PackageNotFoundError, metadata
13
+ from typing import TYPE_CHECKING, Any, Callable, Literal, overload
14
+
15
+ import numpy as np
16
+ import requests
17
+ import torch
18
+ from huggingface_hub import hf_hub_download, snapshot_download
19
+ from torch import Tensor, device
20
+ from tqdm import trange
21
+ from tqdm.autonotebook import tqdm
22
+ from transformers import is_torch_npu_available
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ if TYPE_CHECKING:
27
+ from datasets import Dataset
28
+
29
+ from sentence_transformers.cross_encoder.CrossEncoder import CrossEncoder
30
+ from sentence_transformers.SentenceTransformer import SentenceTransformer
31
+
32
+
33
+ def _convert_to_tensor(a: list | np.ndarray | Tensor) -> Tensor:
34
+ """
35
+ Converts the input `a` to a PyTorch tensor if it is not already a tensor.
36
+
37
+ Args:
38
+ a (Union[list, np.ndarray, Tensor]): The input array or tensor.
39
+
40
+ Returns:
41
+ Tensor: The converted tensor.
42
+ """
43
+ if not isinstance(a, Tensor):
44
+ a = torch.tensor(a)
45
+ return a
46
+
47
+
48
+ def _convert_to_batch(a: Tensor) -> Tensor:
49
+ """
50
+ If the tensor `a` is 1-dimensional, it is unsqueezed to add a batch dimension.
51
+
52
+ Args:
53
+ a (Tensor): The input tensor.
54
+
55
+ Returns:
56
+ Tensor: The tensor with a batch dimension.
57
+ """
58
+ if a.dim() == 1:
59
+ a = a.unsqueeze(0)
60
+ return a
61
+
62
+
63
+ def _convert_to_batch_tensor(a: list | np.ndarray | Tensor) -> Tensor:
64
+ """
65
+ Converts the input data to a tensor with a batch dimension.
66
+
67
+ Args:
68
+ a (Union[list, np.ndarray, Tensor]): The input data to be converted.
69
+
70
+ Returns:
71
+ Tensor: The converted tensor with a batch dimension.
72
+ """
73
+ a = _convert_to_tensor(a)
74
+ a = _convert_to_batch(a)
75
+ return a
76
+
77
+
78
+ def pytorch_cos_sim(a: Tensor, b: Tensor) -> Tensor:
79
+ """
80
+ Computes the cosine similarity between two tensors.
81
+
82
+ Args:
83
+ a (Union[list, np.ndarray, Tensor]): The first tensor.
84
+ b (Union[list, np.ndarray, Tensor]): The second tensor.
85
+
86
+ Returns:
87
+ Tensor: Matrix with res[i][j] = cos_sim(a[i], b[j])
88
+ """
89
+ return cos_sim(a, b)
90
+
91
+
92
+ def cos_sim(a: list | np.ndarray | Tensor, b: list | np.ndarray | Tensor) -> Tensor:
93
+ """
94
+ Computes the cosine similarity between two tensors.
95
+
96
+ Args:
97
+ a (Union[list, np.ndarray, Tensor]): The first tensor.
98
+ b (Union[list, np.ndarray, Tensor]): The second tensor.
99
+
100
+ Returns:
101
+ Tensor: Matrix with res[i][j] = cos_sim(a[i], b[j])
102
+ """
103
+ a = _convert_to_batch_tensor(a)
104
+ b = _convert_to_batch_tensor(b)
105
+
106
+ a_norm = normalize_embeddings(a)
107
+ b_norm = normalize_embeddings(b)
108
+ return torch.mm(a_norm, b_norm.transpose(0, 1))
109
+
110
+
111
+ def pairwise_cos_sim(a: Tensor, b: Tensor) -> Tensor:
112
+ """
113
+ Computes the pairwise cosine similarity cos_sim(a[i], b[i]).
114
+
115
+ Args:
116
+ a (Union[list, np.ndarray, Tensor]): The first tensor.
117
+ b (Union[list, np.ndarray, Tensor]): The second tensor.
118
+
119
+ Returns:
120
+ Tensor: Vector with res[i] = cos_sim(a[i], b[i])
121
+ """
122
+ a = _convert_to_tensor(a)
123
+ b = _convert_to_tensor(b)
124
+
125
+ return pairwise_dot_score(normalize_embeddings(a), normalize_embeddings(b))
126
+
127
+
128
+ def dot_score(a: list | np.ndarray | Tensor, b: list | np.ndarray | Tensor) -> Tensor:
129
+ """
130
+ Computes the dot-product dot_prod(a[i], b[j]) for all i and j.
131
+
132
+ Args:
133
+ a (Union[list, np.ndarray, Tensor]): The first tensor.
134
+ b (Union[list, np.ndarray, Tensor]): The second tensor.
135
+
136
+ Returns:
137
+ Tensor: Matrix with res[i][j] = dot_prod(a[i], b[j])
138
+ """
139
+ a = _convert_to_batch_tensor(a)
140
+ b = _convert_to_batch_tensor(b)
141
+
142
+ return torch.mm(a, b.transpose(0, 1))
143
+
144
+
145
+ def pairwise_dot_score(a: Tensor, b: Tensor) -> Tensor:
146
+ """
147
+ Computes the pairwise dot-product dot_prod(a[i], b[i]).
148
+
149
+ Args:
150
+ a (Union[list, np.ndarray, Tensor]): The first tensor.
151
+ b (Union[list, np.ndarray, Tensor]): The second tensor.
152
+
153
+ Returns:
154
+ Tensor: Vector with res[i] = dot_prod(a[i], b[i])
155
+ """
156
+ a = _convert_to_tensor(a)
157
+ b = _convert_to_tensor(b)
158
+
159
+ return (a * b).sum(dim=-1)
160
+
161
+
162
+ def manhattan_sim(a: list | np.ndarray | Tensor, b: list | np.ndarray | Tensor) -> Tensor:
163
+ """
164
+ Computes the manhattan similarity (i.e., negative distance) between two tensors.
165
+
166
+ Args:
167
+ a (Union[list, np.ndarray, Tensor]): The first tensor.
168
+ b (Union[list, np.ndarray, Tensor]): The second tensor.
169
+
170
+ Returns:
171
+ Tensor: Matrix with res[i][j] = -manhattan_distance(a[i], b[j])
172
+ """
173
+ a = _convert_to_batch_tensor(a)
174
+ b = _convert_to_batch_tensor(b)
175
+
176
+ return -torch.cdist(a, b, p=1.0)
177
+
178
+
179
+ def pairwise_manhattan_sim(a: list | np.ndarray | Tensor, b: list | np.ndarray | Tensor):
180
+ """
181
+ Computes the manhattan similarity (i.e., negative distance) between pairs of tensors.
182
+
183
+ Args:
184
+ a (Union[list, np.ndarray, Tensor]): The first tensor.
185
+ b (Union[list, np.ndarray, Tensor]): The second tensor.
186
+
187
+ Returns:
188
+ Tensor: Vector with res[i] = -manhattan_distance(a[i], b[i])
189
+ """
190
+ a = _convert_to_tensor(a)
191
+ b = _convert_to_tensor(b)
192
+
193
+ return -torch.sum(torch.abs(a - b), dim=-1)
194
+
195
+
196
+ def euclidean_sim(a: list | np.ndarray | Tensor, b: list | np.ndarray | Tensor) -> Tensor:
197
+ """
198
+ Computes the euclidean similarity (i.e., negative distance) between two tensors.
199
+
200
+ Args:
201
+ a (Union[list, np.ndarray, Tensor]): The first tensor.
202
+ b (Union[list, np.ndarray, Tensor]): The second tensor.
203
+
204
+ Returns:
205
+ Tensor: Matrix with res[i][j] = -euclidean_distance(a[i], b[j])
206
+ """
207
+ a = _convert_to_batch_tensor(a)
208
+ b = _convert_to_batch_tensor(b)
209
+
210
+ return -torch.cdist(a, b, p=2.0)
211
+
212
+
213
+ def pairwise_euclidean_sim(a: list | np.ndarray | Tensor, b: list | np.ndarray | Tensor):
214
+ """
215
+ Computes the euclidean distance (i.e., negative distance) between pairs of tensors.
216
+
217
+ Args:
218
+ a (Union[list, np.ndarray, Tensor]): The first tensor.
219
+ b (Union[list, np.ndarray, Tensor]): The second tensor.
220
+
221
+ Returns:
222
+ Tensor: Vector with res[i] = -euclidean_distance(a[i], b[i])
223
+ """
224
+ a = _convert_to_tensor(a)
225
+ b = _convert_to_tensor(b)
226
+
227
+ return -torch.sqrt(torch.sum((a - b) ** 2, dim=-1))
228
+
229
+
230
+ def pairwise_angle_sim(x: Tensor, y: Tensor) -> Tensor:
231
+ """
232
+ Computes the absolute normalized angle distance. See :class:`~sentence_transformers.losses.AnglELoss`
233
+ or https://arxiv.org/abs/2309.12871v1 for more information.
234
+
235
+ Args:
236
+ x (Tensor): The first tensor.
237
+ y (Tensor): The second tensor.
238
+
239
+ Returns:
240
+ Tensor: Vector with res[i] = angle_sim(a[i], b[i])
241
+ """
242
+
243
+ x = _convert_to_tensor(x)
244
+ y = _convert_to_tensor(y)
245
+
246
+ # modified from https://github.com/SeanLee97/AnglE/blob/main/angle_emb/angle.py
247
+ # chunk both tensors to obtain complex components
248
+ a, b = torch.chunk(x, 2, dim=1)
249
+ c, d = torch.chunk(y, 2, dim=1)
250
+
251
+ z = torch.sum(c**2 + d**2, dim=1, keepdim=True)
252
+ re = (a * c + b * d) / z
253
+ im = (b * c - a * d) / z
254
+
255
+ dz = torch.sum(a**2 + b**2, dim=1, keepdim=True) ** 0.5
256
+ dw = torch.sum(c**2 + d**2, dim=1, keepdim=True) ** 0.5
257
+ re /= dz / dw
258
+ im /= dz / dw
259
+
260
+ norm_angle = torch.sum(torch.concat((re, im), dim=1), dim=1)
261
+ return torch.abs(norm_angle)
262
+
263
+
264
+ def normalize_embeddings(embeddings: Tensor) -> Tensor:
265
+ """
266
+ Normalizes the embeddings matrix, so that each sentence embedding has unit length.
267
+
268
+ Args:
269
+ embeddings (Tensor): The input embeddings matrix.
270
+
271
+ Returns:
272
+ Tensor: The normalized embeddings matrix.
273
+ """
274
+ return torch.nn.functional.normalize(embeddings, p=2, dim=1)
275
+
276
+
277
+ @overload
278
+ def truncate_embeddings(embeddings: np.ndarray, truncate_dim: int | None) -> np.ndarray: ...
279
+
280
+
281
+ @overload
282
+ def truncate_embeddings(embeddings: torch.Tensor, truncate_dim: int | None) -> torch.Tensor: ...
283
+
284
+
285
+ def truncate_embeddings(embeddings: np.ndarray | torch.Tensor, truncate_dim: int | None) -> np.ndarray | torch.Tensor:
286
+ """
287
+ Truncates the embeddings matrix.
288
+
289
+ Args:
290
+ embeddings (Union[np.ndarray, torch.Tensor]): Embeddings to truncate.
291
+ truncate_dim (Optional[int]): The dimension to truncate sentence embeddings to. `None` does no truncation.
292
+
293
+ Example:
294
+ >>> from sentence_transformers import SentenceTransformer
295
+ >>> from sentence_transformers.util import truncate_embeddings
296
+ >>> model = SentenceTransformer("tomaarsen/mpnet-base-nli-matryoshka")
297
+ >>> embeddings = model.encode(["It's so nice outside!", "Today is a beautiful day.", "He drove to work earlier"])
298
+ >>> embeddings.shape
299
+ (3, 768)
300
+ >>> model.similarity(embeddings, embeddings)
301
+ tensor([[1.0000, 0.8100, 0.1426],
302
+ [0.8100, 1.0000, 0.2121],
303
+ [0.1426, 0.2121, 1.0000]])
304
+ >>> truncated_embeddings = truncate_embeddings(embeddings, 128)
305
+ >>> truncated_embeddings.shape
306
+ >>> model.similarity(truncated_embeddings, truncated_embeddings)
307
+ tensor([[1.0000, 0.8092, 0.1987],
308
+ [0.8092, 1.0000, 0.2716],
309
+ [0.1987, 0.2716, 1.0000]])
310
+
311
+ Returns:
312
+ Union[np.ndarray, torch.Tensor]: Truncated embeddings.
313
+ """
314
+ return embeddings[..., :truncate_dim]
315
+
316
+
317
+ def paraphrase_mining(
318
+ model,
319
+ sentences: list[str],
320
+ show_progress_bar: bool = False,
321
+ batch_size: int = 32,
322
+ query_chunk_size: int = 5000,
323
+ corpus_chunk_size: int = 100000,
324
+ max_pairs: int = 500000,
325
+ top_k: int = 100,
326
+ score_function: Callable[[Tensor, Tensor], Tensor] = cos_sim,
327
+ ) -> list[list[float | int]]:
328
+ """
329
+ Given a list of sentences / texts, this function performs paraphrase mining. It compares all sentences against all
330
+ other sentences and returns a list with the pairs that have the highest cosine similarity score.
331
+
332
+ Args:
333
+ model (SentenceTransformer): SentenceTransformer model for embedding computation
334
+ sentences (List[str]): A list of strings (texts or sentences)
335
+ show_progress_bar (bool, optional): Plotting of a progress bar. Defaults to False.
336
+ batch_size (int, optional): Number of texts that are encoded simultaneously by the model. Defaults to 32.
337
+ query_chunk_size (int, optional): Search for most similar pairs for #query_chunk_size at the same time. Decrease, to lower memory footprint (increases run-time). Defaults to 5000.
338
+ corpus_chunk_size (int, optional): Compare a sentence simultaneously against #corpus_chunk_size other sentences. Decrease, to lower memory footprint (increases run-time). Defaults to 100000.
339
+ max_pairs (int, optional): Maximal number of text pairs returned. Defaults to 500000.
340
+ top_k (int, optional): For each sentence, we retrieve up to top_k other sentences. Defaults to 100.
341
+ score_function (Callable[[Tensor, Tensor], Tensor], optional): Function for computing scores. By default, cosine similarity. Defaults to cos_sim.
342
+
343
+ Returns:
344
+ List[List[Union[float, int]]]: Returns a list of triplets with the format [score, id1, id2]
345
+ """
346
+
347
+ # Compute embedding for the sentences
348
+ embeddings = model.encode(
349
+ sentences, show_progress_bar=show_progress_bar, batch_size=batch_size, convert_to_tensor=True
350
+ )
351
+
352
+ return paraphrase_mining_embeddings(
353
+ embeddings,
354
+ query_chunk_size=query_chunk_size,
355
+ corpus_chunk_size=corpus_chunk_size,
356
+ max_pairs=max_pairs,
357
+ top_k=top_k,
358
+ score_function=score_function,
359
+ )
360
+
361
+
362
+ def paraphrase_mining_embeddings(
363
+ embeddings: Tensor,
364
+ query_chunk_size: int = 5000,
365
+ corpus_chunk_size: int = 100000,
366
+ max_pairs: int = 500000,
367
+ top_k: int = 100,
368
+ score_function: Callable[[Tensor, Tensor], Tensor] = cos_sim,
369
+ ) -> list[list[float | int]]:
370
+ """
371
+ Given a list of sentences / texts, this function performs paraphrase mining. It compares all sentences against all
372
+ other sentences and returns a list with the pairs that have the highest cosine similarity score.
373
+
374
+ Args:
375
+ embeddings (Tensor): A tensor with the embeddings
376
+ query_chunk_size (int): Search for most similar pairs for #query_chunk_size at the same time. Decrease, to lower memory footprint (increases run-time).
377
+ corpus_chunk_size (int): Compare a sentence simultaneously against #corpus_chunk_size other sentences. Decrease, to lower memory footprint (increases run-time).
378
+ max_pairs (int): Maximal number of text pairs returned.
379
+ top_k (int): For each sentence, we retrieve up to top_k other sentences
380
+ score_function (Callable[[Tensor, Tensor], Tensor]): Function for computing scores. By default, cosine similarity.
381
+
382
+ Returns:
383
+ List[List[Union[float, int]]]: Returns a list of triplets with the format [score, id1, id2]
384
+ """
385
+
386
+ top_k += 1 # A sentence has the highest similarity to itself. Increase +1 as we are interest in distinct pairs
387
+
388
+ # Mine for duplicates
389
+ pairs = queue.PriorityQueue()
390
+ min_score = -1
391
+ num_added = 0
392
+
393
+ for corpus_start_idx in range(0, len(embeddings), corpus_chunk_size):
394
+ for query_start_idx in range(0, len(embeddings), query_chunk_size):
395
+ scores = score_function(
396
+ embeddings[query_start_idx : query_start_idx + query_chunk_size],
397
+ embeddings[corpus_start_idx : corpus_start_idx + corpus_chunk_size],
398
+ )
399
+
400
+ scores_top_k_values, scores_top_k_idx = torch.topk(
401
+ scores, min(top_k, len(scores[0])), dim=1, largest=True, sorted=False
402
+ )
403
+ scores_top_k_values = scores_top_k_values.cpu().tolist()
404
+ scores_top_k_idx = scores_top_k_idx.cpu().tolist()
405
+
406
+ for query_itr in range(len(scores)):
407
+ for top_k_idx, corpus_itr in enumerate(scores_top_k_idx[query_itr]):
408
+ i = query_start_idx + query_itr
409
+ j = corpus_start_idx + corpus_itr
410
+
411
+ if i != j and scores_top_k_values[query_itr][top_k_idx] > min_score:
412
+ pairs.put((scores_top_k_values[query_itr][top_k_idx], i, j))
413
+ num_added += 1
414
+
415
+ if num_added >= max_pairs:
416
+ entry = pairs.get()
417
+ min_score = entry[0]
418
+
419
+ # Get the pairs
420
+ added_pairs = set() # Used for duplicate detection
421
+ pairs_list = []
422
+ while not pairs.empty():
423
+ score, i, j = pairs.get()
424
+ sorted_i, sorted_j = sorted([i, j])
425
+
426
+ if sorted_i != sorted_j and (sorted_i, sorted_j) not in added_pairs:
427
+ added_pairs.add((sorted_i, sorted_j))
428
+ pairs_list.append([score, sorted_i, sorted_j])
429
+
430
+ # Highest scores first
431
+ pairs_list = sorted(pairs_list, key=lambda x: x[0], reverse=True)
432
+ return pairs_list
433
+
434
+
435
+ def information_retrieval(*args, **kwargs) -> list[list[dict[str, int | float]]]:
436
+ """This function is deprecated. Use semantic_search instead"""
437
+ return semantic_search(*args, **kwargs)
438
+
439
+
440
+ def semantic_search(
441
+ query_embeddings: Tensor,
442
+ corpus_embeddings: Tensor,
443
+ query_chunk_size: int = 100,
444
+ corpus_chunk_size: int = 500000,
445
+ top_k: int = 10,
446
+ score_function: Callable[[Tensor, Tensor], Tensor] = cos_sim,
447
+ ) -> list[list[dict[str, int | float]]]:
448
+ """
449
+ This function performs a cosine similarity search between a list of query embeddings and a list of corpus embeddings.
450
+ It can be used for Information Retrieval / Semantic Search for corpora up to about 1 Million entries.
451
+
452
+ Args:
453
+ query_embeddings (Tensor): A 2 dimensional tensor with the query embeddings.
454
+ corpus_embeddings (Tensor): A 2 dimensional tensor with the corpus embeddings.
455
+ query_chunk_size (int, optional): Process 100 queries simultaneously. Increasing that value increases the speed, but requires more memory. Defaults to 100.
456
+ corpus_chunk_size (int, optional): Scans the corpus 100k entries at a time. Increasing that value increases the speed, but requires more memory. Defaults to 500000.
457
+ top_k (int, optional): Retrieve top k matching entries. Defaults to 10.
458
+ score_function (Callable[[Tensor, Tensor], Tensor], optional): Function for computing scores. By default, cosine similarity.
459
+
460
+ Returns:
461
+ List[List[Dict[str, Union[int, float]]]]: A list with one entry for each query. Each entry is a list of dictionaries with the keys 'corpus_id' and 'score', sorted by decreasing cosine similarity scores.
462
+ """
463
+
464
+ if isinstance(query_embeddings, (np.ndarray, np.generic)):
465
+ query_embeddings = torch.from_numpy(query_embeddings)
466
+ elif isinstance(query_embeddings, list):
467
+ query_embeddings = torch.stack(query_embeddings)
468
+
469
+ if len(query_embeddings.shape) == 1:
470
+ query_embeddings = query_embeddings.unsqueeze(0)
471
+
472
+ if isinstance(corpus_embeddings, (np.ndarray, np.generic)):
473
+ corpus_embeddings = torch.from_numpy(corpus_embeddings)
474
+ elif isinstance(corpus_embeddings, list):
475
+ corpus_embeddings = torch.stack(corpus_embeddings)
476
+
477
+ # Check that corpus and queries are on the same device
478
+ if corpus_embeddings.device != query_embeddings.device:
479
+ query_embeddings = query_embeddings.to(corpus_embeddings.device)
480
+
481
+ queries_result_list = [[] for _ in range(len(query_embeddings))]
482
+
483
+ for query_start_idx in range(0, len(query_embeddings), query_chunk_size):
484
+ # Iterate over chunks of the corpus
485
+ for corpus_start_idx in range(0, len(corpus_embeddings), corpus_chunk_size):
486
+ # Compute cosine similarities
487
+ cos_scores = score_function(
488
+ query_embeddings[query_start_idx : query_start_idx + query_chunk_size],
489
+ corpus_embeddings[corpus_start_idx : corpus_start_idx + corpus_chunk_size],
490
+ )
491
+
492
+ # Get top-k scores
493
+ cos_scores_top_k_values, cos_scores_top_k_idx = torch.topk(
494
+ cos_scores, min(top_k, len(cos_scores[0])), dim=1, largest=True, sorted=False
495
+ )
496
+ cos_scores_top_k_values = cos_scores_top_k_values.cpu().tolist()
497
+ cos_scores_top_k_idx = cos_scores_top_k_idx.cpu().tolist()
498
+
499
+ for query_itr in range(len(cos_scores)):
500
+ for sub_corpus_id, score in zip(cos_scores_top_k_idx[query_itr], cos_scores_top_k_values[query_itr]):
501
+ corpus_id = corpus_start_idx + sub_corpus_id
502
+ query_id = query_start_idx + query_itr
503
+ if len(queries_result_list[query_id]) < top_k:
504
+ heapq.heappush(
505
+ queries_result_list[query_id], (score, corpus_id)
506
+ ) # heaqp tracks the quantity of the first element in the tuple
507
+ else:
508
+ heapq.heappushpop(queries_result_list[query_id], (score, corpus_id))
509
+
510
+ # change the data format and sort
511
+ for query_id in range(len(queries_result_list)):
512
+ for doc_itr in range(len(queries_result_list[query_id])):
513
+ score, corpus_id = queries_result_list[query_id][doc_itr]
514
+ queries_result_list[query_id][doc_itr] = {"corpus_id": corpus_id, "score": score}
515
+ queries_result_list[query_id] = sorted(queries_result_list[query_id], key=lambda x: x["score"], reverse=True)
516
+
517
+ return queries_result_list
518
+
519
+
520
+ def mine_hard_negatives(
521
+ dataset: Dataset,
522
+ model: SentenceTransformer,
523
+ corpus: list[str] | None = None,
524
+ cross_encoder: CrossEncoder | None = None,
525
+ range_min: int = 0,
526
+ range_max: int | None = None,
527
+ max_score: float | None = None,
528
+ margin: float | None = None,
529
+ num_negatives: int = 3,
530
+ sampling_strategy: Literal["random", "top"] = "top",
531
+ as_triplets: bool = True,
532
+ batch_size: int = 32,
533
+ faiss_batch_size: int = 16384,
534
+ use_faiss: bool = False,
535
+ verbose: bool = True,
536
+ ) -> Dataset:
537
+ """
538
+ Add hard negatives to a dataset of (anchor, positive) pairs to create (anchor, positive, negative) triplets or
539
+ (anchor, positive, negative_1, ..., negative_n) tuples.
540
+
541
+ Hard negative mining is a technique to improve the quality of a dataset by adding hard negatives, which are
542
+ texts that may appear similar to the anchor, but are not. Using hard negatives can improve the performance of
543
+ models trained on the dataset.
544
+
545
+ This function uses a SentenceTransformer model to embed the sentences in the dataset, and then finds the closest
546
+ matches to each anchor sentence in the dataset. It then samples negatives from the closest matches, optionally
547
+ using a CrossEncoder model to rescore the candidates.
548
+
549
+ You can influence the candidate negative selection in various ways:
550
+
551
+ - **range_min**: Minimum rank of the closest matches to consider as negatives: useful to skip the most similar texts to
552
+ avoid marking texts as negative that are actually positives.
553
+ - **range_max**: Maximum rank of the closest matches to consider as negatives: useful to limit the number of candidates
554
+ to sample negatives from. A lower value makes processing faster, but may result in less candidate negatives that
555
+ satisfy the margin or max_score conditions.
556
+ - **max_score**: Maximum score to consider as a negative: useful to skip candidates that are too similar to the anchor.
557
+ - **margin**: Margin for hard negative mining: useful to skip candidates negatives whose similarity to the anchor is
558
+ within a certain margin of the positive pair. A value of 0 can be used to enforce that the negative is always
559
+ further away from the anchor than the positive.
560
+ - **sampling_strategy**: Sampling strategy for negatives: "top" or "random". "top" will always sample the top n
561
+ candidates as negatives, while "random" will sample n negatives randomly from the candidates that satisfy the
562
+ margin or max_score conditions.
563
+
564
+ Example:
565
+
566
+ >>> from sentence_transformers.util import mine_hard_negatives
567
+ >>> from sentence_transformers import SentenceTransformer
568
+ >>> from datasets import load_dataset
569
+ >>> # Load a Sentence Transformer model
570
+ >>> model = SentenceTransformer("all-MiniLM-L6-v2")
571
+ >>>
572
+ >>> # Load a dataset to mine hard negatives from
573
+ >>> dataset = load_dataset("sentence-transformers/natural-questions", split="train")
574
+ >>> dataset
575
+ Dataset({
576
+ features: ['query', 'answer'],
577
+ num_rows: 100231
578
+ })
579
+ >>> dataset = mine_hard_negatives(
580
+ ... dataset=dataset,
581
+ ... model=model,
582
+ ... range_min=10,
583
+ ... range_max=50,
584
+ ... max_score=0.8,
585
+ ... margin=0.1,
586
+ ... num_negatives=5,
587
+ ... sampling_strategy="random",
588
+ ... batch_size=128,
589
+ ... use_faiss=True,
590
+ ... )
591
+ Batches: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 784/784 [00:43<00:00, 17.83it/s]
592
+ Batches: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 784/784 [00:07<00:00, 99.60it/s]
593
+ Querying FAISS index: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████| 784/784 [00:00<00:00, 884.99it/s]
594
+ Metric Positive Negative Difference
595
+ Count 100,231 431,255 431,255
596
+ Mean 0.6866 0.4289 0.2804
597
+ Median 0.7010 0.4193 0.2740
598
+ Std 0.1125 0.0754 0.0999
599
+ Min 0.0303 0.1720 0.1001
600
+ 25% 0.6221 0.3747 0.1991
601
+ 50% 0.7010 0.4193 0.2740
602
+ 75% 0.7667 0.4751 0.3530
603
+ Max 0.9584 0.7743 0.7003
604
+ Skipped 1289492 potential negatives (25.23%) due to the margin of 0.1.
605
+ Skipped 39 potential negatives (0.00%) due to the maximum score of 0.8.
606
+ Could not find enough negatives for 69900 samples (13.95%). Consider adjusting the range_max, range_min, margin and max_score parameters if you'd like to find more valid negatives.
607
+ >>> # Note: The minimum similarity difference is 0.1001 due to our margin of 0.1
608
+ >>> dataset
609
+ Dataset({
610
+ features: ['query', 'answer', 'negative'],
611
+ num_rows: 431255
612
+ })
613
+ >>> dataset[0]
614
+ {
615
+ 'query': 'when did richmond last play in a preliminary final',
616
+ 'answer': "Richmond Football Club Richmond began 2017 with 5 straight wins, a feat it had not achieved since 1995. A series of close losses hampered the Tigers throughout the middle of the season, including a 5-point loss to the Western Bulldogs, 2-point loss to Fremantle, and a 3-point loss to the Giants. Richmond ended the season strongly with convincing victories over Fremantle and St Kilda in the final two rounds, elevating the club to 3rd on the ladder. Richmond's first final of the season against the Cats at the MCG attracted a record qualifying final crowd of 95,028; the Tigers won by 51 points. Having advanced to the first preliminary finals for the first time since 2001, Richmond defeated Greater Western Sydney by 36 points in front of a crowd of 94,258 to progress to the Grand Final against Adelaide, their first Grand Final appearance since 1982. The attendance was 100,021, the largest crowd to a grand final since 1986. The Crows led at quarter time and led by as many as 13, but the Tigers took over the game as it progressed and scored seven straight goals at one point. They eventually would win by 48 points – 16.12 (108) to Adelaide's 8.12 (60) – to end their 37-year flag drought.[22] Dustin Martin also became the first player to win a Premiership medal, the Brownlow Medal and the Norm Smith Medal in the same season, while Damien Hardwick was named AFL Coaches Association Coach of the Year. Richmond's jump from 13th to premiers also marked the biggest jump from one AFL season to the next.",
617
+ 'negative': "2018 NRL Grand Final The 2018 NRL Grand Final was the conclusive and premiership-deciding game of the 2018 National Rugby League season and was played on Sunday September 30 at Sydney's ANZ Stadium.[1] The match was contested between minor premiers the Sydney Roosters and defending premiers the Melbourne Storm. In front of a crowd of 82,688, Sydney won the match 21–6 to claim their 14th premiership title and their first since 2013. Roosters five-eighth Luke Keary was awarded the Clive Churchill Medal as the game's official man of the match."
618
+ }
619
+ >>> dataset.push_to_hub("natural-questions-hard-negatives", "triplet-all")
620
+
621
+ Args:
622
+ dataset (Dataset): A dataset containing (anchor, positive) pairs.
623
+ model (SentenceTransformer): A SentenceTransformer model to use for embedding the sentences.
624
+ corpus (List[str], optional): A list containing documents as strings that will be used as candidate negatives
625
+ in addition to the second column in `dataset`. Defaults to None, in which case the second column in
626
+ `dataset` will exclusively be used as the negative candidate corpus.
627
+ cross_encoder (CrossEncoder, optional): A CrossEncoder model to use for rescoring the candidates. Defaults to None.
628
+ range_min (int): Minimum rank of the closest matches to consider as negatives. Defaults to 0.
629
+ range_max (int, optional): Maximum rank of the closest matches to consider as negatives. Defaults to None.
630
+ max_score (float, optional): Maximum score to consider as a negative. Defaults to None.
631
+ margin (float, optional): Margin for hard negative mining. Defaults to None.
632
+ num_negatives (int): Number of negatives to sample. Defaults to 3.
633
+ sampling_strategy (Literal["random", "top"]): Sampling strategy for negatives: "top" or "random". Defaults to "top".
634
+ as_triplets (bool): If True, returns up to `num_negatives` (anchor, positive, negative) triplets for each input sample.
635
+ If False, returns 1 (anchor, positive, negative_1, ..., negative_n) tuple for each input sample. Defaults to True.
636
+ batch_size (int): Batch size for encoding the dataset. Defaults to 32.
637
+ faiss_batch_size (int): Batch size for FAISS top-k search. Defaults to 16384.
638
+ use_faiss (bool): Whether to use FAISS for similarity search. May be recommended for large datasets. Defaults to False.
639
+ verbose (bool): Whether to print statistics and logging. Defaults to True.
640
+
641
+ Returns:
642
+ Dataset: A dataset containing (anchor, positive, negative) triplets or (anchor, positive, negative_1, ..., negative_n) tuples.
643
+ """
644
+ if not is_datasets_available():
645
+ raise ImportError("Please install `datasets` to use this function: `pip install datasets`.")
646
+
647
+ from datasets import Dataset
648
+
649
+ # If a dataset has duplicate queries, assume that all duplicates are positive pairs.
650
+ columns = dataset.column_names
651
+ if len(columns) != 2:
652
+ raise ValueError("Dataset must contain exactly two columns.")
653
+
654
+ # To avoid re-embedding the same query multiple times, we keep a counter of the number of positives per query
655
+ positives_per_query = list(dataset.to_pandas().groupby(columns[0]).count().to_dict()[columns[1]].values())
656
+ max_positives = max(positives_per_query)
657
+
658
+ if range_max is None:
659
+ if margin is not None or max_score is not None:
660
+ # max_positives + 10 * num_negatives negatives because some might be skipped, and range_min skipped
661
+ range_max = range_min + (num_negatives * 10) + max_positives
662
+ else:
663
+ # max_positives, num_negatives negatives, and range_min skipped
664
+ range_max = range_min + num_negatives + max_positives
665
+ if range_max > 2048 and use_faiss:
666
+ # FAISS on GPU can only retrieve up to 2048 documents per query
667
+ range_max = 2048
668
+ if verbose:
669
+ print("Using FAISS, we can only retrieve up to 2048 documents per query. Setting range_max to 2048.")
670
+ if verbose:
671
+ print(f"Setting range_max to {range_max} based on the provided parameters.")
672
+
673
+ log_counters = {}
674
+ queries = dataset[columns[0]]
675
+ positives = dataset[columns[1]]
676
+ separate_corpus = corpus is not None
677
+ if not separate_corpus:
678
+ corpus = positives
679
+
680
+ # Deduplicate the corpus
681
+ # make sure all the positives are also in the corpus and de-duplicate it.
682
+ corpus = list(set(corpus) | set(positives))
683
+
684
+ # corpus_idx maps the corpus text into its position in the corpus
685
+ # This position does not necessarily matches the original corpus, as it was de-duplicated.
686
+ corpus_idx = {text: idx for idx, text in enumerate(corpus)}
687
+
688
+ # Deduplicate the queries, but keep the original one for later reference.
689
+ all_queries = queries.copy()
690
+ queries = list(set(queries))
691
+ queries_idx = {query: idx for idx, query in enumerate(queries)}
692
+ n_queries = len(queries)
693
+ batch_idx = torch.arange(n_queries).unsqueeze(-1)
694
+
695
+ device = model.device
696
+
697
+ if n_queries != len(all_queries) and verbose:
698
+ print(f"Found {n_queries} unique queries out of {len(all_queries)} total queries.")
699
+
700
+ if max_positives > 1:
701
+ avg_positives_per_query = np.mean(positives_per_query)
702
+ print(f"Found an average of {avg_positives_per_query:.3f} positives per query.")
703
+
704
+ if use_faiss:
705
+ import faiss
706
+
707
+ index = faiss.IndexFlatIP(model.get_sentence_embedding_dimension())
708
+ # Move the index to the GPU if available
709
+ try:
710
+ co = faiss.GpuMultipleClonerOptions()
711
+ co.shard = True
712
+ co.useFloat16 = True
713
+ index: faiss.IndexFlatIP = faiss.index_cpu_to_all_gpus(index, co=co)
714
+ except Exception:
715
+ pass
716
+
717
+ corpus_embeddings = model.encode(
718
+ corpus, batch_size=batch_size, normalize_embeddings=True, convert_to_numpy=True, show_progress_bar=True
719
+ )
720
+ query_embeddings = model.encode(
721
+ queries, batch_size=batch_size, normalize_embeddings=True, convert_to_numpy=True, show_progress_bar=True
722
+ )
723
+ index.add(corpus_embeddings)
724
+
725
+ scores_list = []
726
+ indices_list = []
727
+ # Iterate over query embeddings in batches so we can track the progress
728
+ for i in trange(0, len(query_embeddings), faiss_batch_size, desc="Querying FAISS index"):
729
+ query_chunk = query_embeddings[i : i + faiss_batch_size]
730
+ scores, indices = index.search(query_chunk, k=range_max + 1)
731
+ scores_list.append(scores)
732
+ indices_list.append(indices)
733
+ scores = torch.from_numpy(np.concatenate(scores_list, axis=0)).to(device)
734
+ indices = torch.from_numpy(np.concatenate(indices_list, axis=0)).to(device)
735
+
736
+ else:
737
+ # Embed the corpus and the queries
738
+ corpus_embeddings = model.encode(
739
+ corpus, batch_size=batch_size, normalize_embeddings=True, convert_to_numpy=True, show_progress_bar=True
740
+ )
741
+ query_embeddings = model.encode(
742
+ queries, batch_size=batch_size, normalize_embeddings=True, convert_to_numpy=True, show_progress_bar=True
743
+ )
744
+ scores = model.similarity(query_embeddings, corpus_embeddings).to(device)
745
+
746
+ # Keep only the range_max + max_positives highest scores. We offset by 1 to potentially include the positive pair
747
+ scores, indices = torch.topk(scores, k=range_max + max_positives, dim=1)
748
+
749
+ # As we may have duplicated queries (i.e., a single query with multiple positives),
750
+ # We keep track, for each unique query, of where their positives are in the list of positives (positive_indices).
751
+ # Note that as queries may have differing numbers of positives, we cannot guarantee that this is a fixed-length matrix.
752
+ positive_indices = [[] for _ in range(n_queries)]
753
+
754
+ for query, positive in zip(all_queries, positives):
755
+ query_idx = queries_idx[query]
756
+ positive_indices[query_idx].append(corpus_idx[positive])
757
+
758
+ n_positives = [len(p) for p in positive_indices]
759
+
760
+ # re-sort the positives and all_queries according to the deduplicated queries
761
+ positives = []
762
+ all_queries = []
763
+ for idx in range(n_queries):
764
+ positives.extend([corpus[doc_idx] for doc_idx in positive_indices[idx]])
765
+ all_queries.extend([queries[idx]] * n_positives[idx])
766
+
767
+ positive_indices = [torch.tensor(p, device=device) for p in positive_indices]
768
+
769
+ # Compute the positive scores
770
+ query_embeddings = query_embeddings[[idx for idx in range(n_queries) for _ in range(n_positives[idx])]]
771
+ positive_embeddings = corpus_embeddings[torch.cat(positive_indices).tolist()]
772
+ positive_scores = model.similarity_pairwise(query_embeddings, positive_embeddings).to(device)
773
+
774
+ del query_embeddings
775
+ del positive_embeddings
776
+ del corpus_embeddings
777
+
778
+ # Rescore with cross_encoder
779
+ if cross_encoder is not None and (margin is not None or max_score is not None):
780
+ for idx, candidate_idx in tqdm(enumerate(indices), desc="Rescoring with CrossEncoder", total=len(indices)):
781
+ query = queries[idx]
782
+ candidate_passages = [corpus[_idx] for _idx in candidate_idx]
783
+ pred_scores = cross_encoder.predict(
784
+ list(zip([query] * (range_max + 1), candidate_passages)),
785
+ batch_size=batch_size,
786
+ convert_to_tensor=True,
787
+ )
788
+ scores[idx] = pred_scores
789
+ positive_scores = cross_encoder.predict(
790
+ list(zip(all_queries, positives)),
791
+ batch_size=batch_size,
792
+ convert_to_tensor=True,
793
+ )
794
+
795
+ # for each query, create a mask that is True for the positives and False for the negatives in the indices
796
+ positive_mask = torch.stack([torch.isin(indices[q_idx], positive_indices[q_idx]) for q_idx in range(n_queries)])
797
+
798
+ # Scores is a [num_queries, range_max] tensor, where we set the values to -inf to disqualify the corresponding
799
+ # positive candidates
800
+ scores[positive_mask] = -float("inf")
801
+
802
+ num_candidates = scores.numel()
803
+
804
+ # Remove based on margin
805
+ if margin is not None:
806
+ # If we have a margin, we will remove candidates that are too close to the positive pair
807
+ # If there are multiple positives, we need to define which one to use for the margin
808
+ # To be on the safe side, we will use the _minimum_ positive score (i.e., harder positive) for the margin
809
+ max_positive_scores = torch.empty(n_queries, device=positive_scores.device, dtype=positive_scores.dtype)
810
+ start_idx = 0
811
+ for q_idx in range(n_queries):
812
+ max_positive_scores[q_idx] = torch.min(positive_scores[start_idx : start_idx + n_positives[q_idx]])
813
+ start_idx += n_positives[q_idx - 1]
814
+
815
+ removed_indices = scores + margin > max_positive_scores.repeat(scores.size(1), 1).T
816
+ scores[removed_indices] = -float("inf")
817
+
818
+ num_skipped = removed_indices.sum().item()
819
+ if num_skipped:
820
+ log_counters["margin"] = {
821
+ "skipped": num_skipped,
822
+ "ratio": num_skipped / num_candidates,
823
+ }
824
+ num_candidates -= num_skipped
825
+
826
+ # Remove based on max_score
827
+ if max_score is not None:
828
+ removed_indices = scores > max_score
829
+ scores[removed_indices] = -float("inf")
830
+
831
+ num_skipped = removed_indices.sum().item()
832
+ if num_skipped:
833
+ log_counters["max_score"] = {
834
+ "skipped": num_skipped,
835
+ "ratio": num_skipped / num_candidates,
836
+ }
837
+
838
+ # Grab the top negative candidates and remove the first range_min candidates
839
+ negative_scores, local_indices = torch.topk(scores, k=range_max, dim=1)
840
+ indices = indices[batch_idx, local_indices]
841
+
842
+ if range_min:
843
+ indices = indices[:, range_min:]
844
+ negative_scores = negative_scores[:, range_min:]
845
+
846
+ # Either grab the top negatives or sample randomly
847
+ if sampling_strategy == "top":
848
+ indices = indices[:, :num_negatives]
849
+ negative_scores = negative_scores[:, :num_negatives]
850
+
851
+ elif sampling_strategy == "random":
852
+ # Prevent sampling -inf values if possible
853
+ num_options = indices.size(1) - negative_scores.isinf().sum(1)
854
+ num_options = num_options.clamp(min=num_negatives)
855
+ # Randomly sample negatives from each row
856
+ sampled_idx = [random.sample(range(options), k=num_negatives) for options in num_options]
857
+ indices = indices[batch_idx, sampled_idx]
858
+ negative_scores = negative_scores[batch_idx, sampled_idx]
859
+ # Resort the indices and scores
860
+ negative_scores, local_indices = negative_scores.sort(dim=1, descending=True)
861
+ indices = indices[batch_idx, local_indices]
862
+
863
+ # repeat indices and negative_scores by the number of positives of each query
864
+ indices = torch.cat([indices[idx].repeat(n_positives[idx], 1) for idx in range(n_queries)])
865
+ negative_scores = torch.cat([negative_scores[idx].repeat(n_positives[idx], 1) for idx in range(n_queries)])
866
+
867
+ if as_triplets:
868
+ # If calling as triples and there are multiple positives per query, we will explode the dataset into triplets.
869
+ indices_to_keep = negative_scores != -float("inf")
870
+ anchor_indices = torch.empty_like(indices)
871
+ pos_indices = torch.empty_like(indices)
872
+
873
+ indices = indices[indices_to_keep]
874
+ negative_scores = negative_scores[indices_to_keep]
875
+
876
+ # the anchor_indices matrix is shaped [n_total_queries, n_negatives]
877
+ start_idx = 0
878
+ for q_idx in range(n_queries):
879
+ anchor_indices[start_idx : start_idx + n_positives[q_idx]] = torch.tensor(q_idx).repeat(
880
+ n_positives[q_idx], num_negatives
881
+ )
882
+ pos_indices[start_idx : start_idx + n_positives[q_idx]] = (
883
+ positive_indices[q_idx].repeat(num_negatives, 1).T
884
+ )
885
+ start_idx += n_positives[q_idx]
886
+
887
+ anchor_indices = anchor_indices[indices_to_keep]
888
+ positive_indices = pos_indices[indices_to_keep]
889
+
890
+ triplets_data = {
891
+ columns[0]: [],
892
+ columns[1]: [],
893
+ "negative": [],
894
+ }
895
+
896
+ for anchor_idx, negative_idx, positive_idx in zip(anchor_indices, indices, positive_indices):
897
+ triplets_data[columns[0]].append(queries[anchor_idx])
898
+ triplets_data[columns[1]].append(corpus[positive_idx])
899
+ triplets_data["negative"].append(corpus[negative_idx])
900
+ difference_scores = positive_scores.repeat(num_negatives, 1).T[indices_to_keep] - negative_scores
901
+
902
+ else:
903
+ # Keep only indices where num_negative negatives were found
904
+ indices_to_keep = (negative_scores != -float("inf")).all(dim=1)
905
+ negative_scores = negative_scores[indices_to_keep]
906
+ indices = indices[indices_to_keep]
907
+
908
+ triplets_data = {
909
+ columns[0]: [all_queries[idx] for idx, keep in enumerate(indices_to_keep) if keep],
910
+ columns[1]: [positives[idx] for idx, keep in enumerate(indices_to_keep) if keep],
911
+ **{
912
+ f"negative_{i}": [corpus[neg_idx] for neg_idx in neg_indices]
913
+ for i, neg_indices in enumerate(indices.T, start=1)
914
+ },
915
+ }
916
+ negative_scores = negative_scores.flatten()
917
+ difference_scores = positive_scores.repeat(num_negatives, 1).T[indices_to_keep].flatten() - negative_scores
918
+
919
+ if len(triplets_data) == 0:
920
+ raise ValueError("No triplets could be generated. Please check the parameters and dataset.")
921
+ triplets_dataset = Dataset.from_dict(triplets_data)
922
+
923
+ # Report some statistics
924
+ if verbose:
925
+ row_format = "{:<6} {:>14} {:>14} {:>14}"
926
+ formatter = lambda value: (f"{value.item():.4f}" if isinstance(value, torch.Tensor) else f"{value:,}")
927
+ print(row_format.format("Metric", "Positive", "Negative", "Difference"))
928
+ print(
929
+ row_format.format(
930
+ "Count",
931
+ formatter(len(positive_scores)),
932
+ formatter(len(negative_scores)),
933
+ "",
934
+ )
935
+ )
936
+ for metric, function in [
937
+ ("mean", torch.mean),
938
+ ("median", torch.median),
939
+ ("std", torch.std),
940
+ ("min", torch.min),
941
+ ("25%", lambda scores: torch.quantile(scores.float(), q=0.25)),
942
+ ("50%", lambda scores: torch.quantile(scores.float(), q=0.5)),
943
+ ("75%", lambda scores: torch.quantile(scores.float(), q=0.75)),
944
+ ("max", torch.max),
945
+ ]:
946
+ print(
947
+ row_format.format(
948
+ metric.capitalize(),
949
+ formatter(function(positive_scores)),
950
+ formatter(function(negative_scores)),
951
+ formatter(function(difference_scores)),
952
+ )
953
+ )
954
+
955
+ if "margin" in log_counters:
956
+ print(
957
+ f"Skipped {log_counters['margin']['skipped']} potential negatives ({log_counters['margin']['ratio']:.2%}) due to the margin of {margin}."
958
+ )
959
+ if "max_score" in log_counters:
960
+ print(
961
+ f"Skipped {log_counters['max_score']['skipped']} potential negatives ({log_counters['max_score']['ratio']:.2%}) due to the maximum score of {max_score}."
962
+ )
963
+
964
+ missing_negatives = (num_negatives * len(dataset)) - len(negative_scores)
965
+ if missing_negatives > 0:
966
+ solutions = ["range_max"]
967
+ if range_min > 0:
968
+ solutions.append("range_min")
969
+ if margin is not None:
970
+ solutions.append("margin")
971
+ if max_score is not None:
972
+ solutions.append("max_score")
973
+ considerations = ", ".join(solutions[:-1])
974
+ if len(solutions) > 1:
975
+ considerations += " and " + solutions[-1]
976
+ missing_negatives_ratio = missing_negatives / (num_negatives * len(dataset))
977
+ print(
978
+ f"Could not find enough negatives for {missing_negatives} samples ({missing_negatives_ratio:.2%})."
979
+ f" Consider adjusting the {considerations} parameter{'s' if len(solutions) > 1 else ''} if you'd like to find more valid negatives."
980
+ )
981
+
982
+ return triplets_dataset
983
+
984
+
985
+ def http_get(url: str, path: str) -> None:
986
+ """
987
+ Downloads a URL to a given path on disk.
988
+
989
+ Args:
990
+ url (str): The URL to download.
991
+ path (str): The path to save the downloaded file.
992
+
993
+ Raises:
994
+ requests.HTTPError: If the HTTP request returns a non-200 status code.
995
+
996
+ Returns:
997
+ None
998
+ """
999
+ if os.path.dirname(path) != "":
1000
+ os.makedirs(os.path.dirname(path), exist_ok=True)
1001
+
1002
+ req = requests.get(url, stream=True)
1003
+ if req.status_code != 200:
1004
+ print(f"Exception when trying to download {url}. Response {req.status_code}", file=sys.stderr)
1005
+ req.raise_for_status()
1006
+ return
1007
+
1008
+ download_filepath = path + "_part"
1009
+ with open(download_filepath, "wb") as file_binary:
1010
+ content_length = req.headers.get("Content-Length")
1011
+ total = int(content_length) if content_length is not None else None
1012
+ progress = tqdm(unit="B", total=total, unit_scale=True)
1013
+ for chunk in req.iter_content(chunk_size=1024):
1014
+ if chunk: # filter out keep-alive new chunks
1015
+ progress.update(len(chunk))
1016
+ file_binary.write(chunk)
1017
+
1018
+ os.rename(download_filepath, path)
1019
+ progress.close()
1020
+
1021
+
1022
+ def batch_to_device(batch: dict[str, Any], target_device: device) -> dict[str, Any]:
1023
+ """
1024
+ Send a PyTorch batch (i.e., a dictionary of string keys to Tensors) to a device (e.g. "cpu", "cuda", "mps").
1025
+
1026
+ Args:
1027
+ batch (Dict[str, Tensor]): The batch to send to the device.
1028
+ target_device (torch.device): The target device (e.g. "cpu", "cuda", "mps").
1029
+
1030
+ Returns:
1031
+ Dict[str, Tensor]: The batch with tensors sent to the target device.
1032
+ """
1033
+ for key in batch:
1034
+ if isinstance(batch[key], Tensor):
1035
+ batch[key] = batch[key].to(target_device)
1036
+ return batch
1037
+
1038
+
1039
+ def fullname(o) -> str:
1040
+ """
1041
+ Gives a full name (package_name.class_name) for a class / object in Python. Will
1042
+ be used to load the correct classes from JSON files
1043
+
1044
+ Args:
1045
+ o: The object for which to get the full name.
1046
+
1047
+ Returns:
1048
+ str: The full name of the object.
1049
+
1050
+ Example:
1051
+ >>> from sentence_transformers.losses import MultipleNegativesRankingLoss
1052
+ >>> from sentence_transformers import SentenceTransformer
1053
+ >>> from sentence_transformers.util import fullname
1054
+ >>> model = SentenceTransformer('all-MiniLM-L6-v2')
1055
+ >>> loss = MultipleNegativesRankingLoss(model)
1056
+ >>> fullname(loss)
1057
+ 'sentence_transformers.losses.MultipleNegativesRankingLoss.MultipleNegativesRankingLoss'
1058
+ """
1059
+
1060
+ module = o.__class__.__module__
1061
+ if module is None or module == str.__class__.__module__:
1062
+ return o.__class__.__name__ # Avoid reporting __builtin__
1063
+ else:
1064
+ return module + "." + o.__class__.__name__
1065
+
1066
+
1067
+ def import_from_string(dotted_path: str) -> type:
1068
+ """
1069
+ Import a dotted module path and return the attribute/class designated by the
1070
+ last name in the path. Raise ImportError if the import failed.
1071
+
1072
+ Args:
1073
+ dotted_path (str): The dotted module path.
1074
+
1075
+ Returns:
1076
+ Any: The attribute/class designated by the last name in the path.
1077
+
1078
+ Raises:
1079
+ ImportError: If the import failed.
1080
+
1081
+ Example:
1082
+ >>> import_from_string('sentence_transformers.losses.MultipleNegativesRankingLoss')
1083
+ <class 'sentence_transformers.losses.MultipleNegativesRankingLoss.MultipleNegativesRankingLoss'>
1084
+ """
1085
+ try:
1086
+ module_path, class_name = dotted_path.rsplit(".", 1)
1087
+ except ValueError:
1088
+ msg = f"{dotted_path} doesn't look like a module path"
1089
+ raise ImportError(msg)
1090
+
1091
+ try:
1092
+ module = importlib.import_module(dotted_path)
1093
+ except Exception:
1094
+ module = importlib.import_module(module_path)
1095
+
1096
+ try:
1097
+ return getattr(module, class_name)
1098
+ except AttributeError:
1099
+ msg = f'Module "{module_path}" does not define a "{class_name}" attribute/class'
1100
+ raise ImportError(msg)
1101
+
1102
+
1103
+ def community_detection(
1104
+ embeddings: torch.Tensor | np.ndarray,
1105
+ threshold: float = 0.75,
1106
+ min_community_size: int = 10,
1107
+ batch_size: int = 1024,
1108
+ show_progress_bar: bool = False,
1109
+ ) -> list[list[int]]:
1110
+ """
1111
+ Function for Fast Community Detection.
1112
+
1113
+ Finds in the embeddings all communities, i.e. embeddings that are close (closer than threshold).
1114
+ Returns only communities that are larger than min_community_size. The communities are returned
1115
+ in decreasing order. The first element in each list is the central point in the community.
1116
+
1117
+ Args:
1118
+ embeddings (torch.Tensor or numpy.ndarray): The input embeddings.
1119
+ threshold (float): The threshold for determining if two embeddings are close. Defaults to 0.75.
1120
+ min_community_size (int): The minimum size of a community to be considered. Defaults to 10.
1121
+ batch_size (int): The batch size for computing cosine similarity scores. Defaults to 1024.
1122
+ show_progress_bar (bool): Whether to show a progress bar during computation. Defaults to False.
1123
+
1124
+ Returns:
1125
+ List[List[int]]: A list of communities, where each community is represented as a list of indices.
1126
+ """
1127
+ if not isinstance(embeddings, torch.Tensor):
1128
+ embeddings = torch.tensor(embeddings)
1129
+
1130
+ threshold = torch.tensor(threshold, device=embeddings.device)
1131
+ embeddings = normalize_embeddings(embeddings)
1132
+
1133
+ extracted_communities = []
1134
+
1135
+ # Maximum size for community
1136
+ min_community_size = min(min_community_size, len(embeddings))
1137
+ sort_max_size = min(max(2 * min_community_size, 50), len(embeddings))
1138
+
1139
+ for start_idx in tqdm(
1140
+ range(0, len(embeddings), batch_size), desc="Finding clusters", disable=not show_progress_bar
1141
+ ):
1142
+ # Compute cosine similarity scores
1143
+ cos_scores = embeddings[start_idx : start_idx + batch_size] @ embeddings.T
1144
+
1145
+ # Use a torch-heavy approach if the embeddings are on CUDA, otherwise a loop-heavy one
1146
+ if embeddings.device.type in ["cuda", "npu"]:
1147
+ # Threshold the cos scores and determine how many close embeddings exist per embedding
1148
+ threshold_mask = cos_scores >= threshold
1149
+ row_wise_count = threshold_mask.sum(1)
1150
+
1151
+ # Only consider embeddings with enough close other embeddings
1152
+ large_enough_mask = row_wise_count >= min_community_size
1153
+ if not large_enough_mask.any():
1154
+ continue
1155
+
1156
+ row_wise_count = row_wise_count[large_enough_mask]
1157
+ cos_scores = cos_scores[large_enough_mask]
1158
+
1159
+ # The max is the largest potential community, so we use that in topk
1160
+ k = row_wise_count.max()
1161
+ _, top_k_indices = cos_scores.topk(k=k, largest=True)
1162
+
1163
+ # Use the row-wise count to slice the indices
1164
+ for count, indices in zip(row_wise_count, top_k_indices):
1165
+ extracted_communities.append(indices[:count].tolist())
1166
+ else:
1167
+ # Minimum size for a community
1168
+ top_k_values, _ = cos_scores.topk(k=min_community_size, largest=True)
1169
+
1170
+ # Filter for rows >= min_threshold
1171
+ for i in range(len(top_k_values)):
1172
+ if top_k_values[i][-1] >= threshold:
1173
+ # Only check top k most similar entries
1174
+ top_val_large, top_idx_large = cos_scores[i].topk(k=sort_max_size, largest=True)
1175
+
1176
+ # Check if we need to increase sort_max_size
1177
+ while top_val_large[-1] > threshold and sort_max_size < len(embeddings):
1178
+ sort_max_size = min(2 * sort_max_size, len(embeddings))
1179
+ top_val_large, top_idx_large = cos_scores[i].topk(k=sort_max_size, largest=True)
1180
+
1181
+ extracted_communities.append(top_idx_large[top_val_large >= threshold].tolist())
1182
+
1183
+ # Largest cluster first
1184
+ extracted_communities = sorted(extracted_communities, key=lambda x: len(x), reverse=True)
1185
+
1186
+ # Step 2) Remove overlapping communities
1187
+ unique_communities = []
1188
+ extracted_ids = set()
1189
+
1190
+ for cluster_id, community in enumerate(extracted_communities):
1191
+ non_overlapped_community = []
1192
+ for idx in community:
1193
+ if idx not in extracted_ids:
1194
+ non_overlapped_community.append(idx)
1195
+
1196
+ if len(non_overlapped_community) >= min_community_size:
1197
+ unique_communities.append(non_overlapped_community)
1198
+ extracted_ids.update(non_overlapped_community)
1199
+
1200
+ unique_communities = sorted(unique_communities, key=lambda x: len(x), reverse=True)
1201
+
1202
+ return unique_communities
1203
+
1204
+
1205
+ ##################
1206
+ #
1207
+ ######################
1208
+
1209
+
1210
+ class disabled_tqdm(tqdm):
1211
+ """
1212
+ Class to override `disable` argument in case progress bars are globally disabled.
1213
+
1214
+ Taken from https://github.com/tqdm/tqdm/issues/619#issuecomment-619639324.
1215
+ """
1216
+
1217
+ def __init__(self, *args, **kwargs):
1218
+ kwargs["disable"] = True
1219
+ super().__init__(*args, **kwargs)
1220
+
1221
+ def __delattr__(self, attr: str) -> None:
1222
+ """Fix for https://github.com/huggingface/huggingface_hub/issues/1603"""
1223
+ try:
1224
+ super().__delattr__(attr)
1225
+ except AttributeError:
1226
+ if attr != "_lock":
1227
+ raise
1228
+
1229
+
1230
+ @contextmanager
1231
+ def disable_logging(highest_level=logging.CRITICAL):
1232
+ """
1233
+ A context manager that will prevent any logging messages
1234
+ triggered during the body from being processed.
1235
+
1236
+ Args:
1237
+ highest_level: the maximum logging level allowed.
1238
+ """
1239
+
1240
+ previous_level = logging.root.manager.disable
1241
+
1242
+ logging.disable(highest_level)
1243
+
1244
+ try:
1245
+ yield
1246
+ finally:
1247
+ logging.disable(previous_level)
1248
+
1249
+
1250
+ def is_sentence_transformer_model(
1251
+ model_name_or_path: str,
1252
+ token: bool | str | None = None,
1253
+ cache_folder: str | None = None,
1254
+ revision: str | None = None,
1255
+ local_files_only: bool = False,
1256
+ ) -> bool:
1257
+ """
1258
+ Checks if the given model name or path corresponds to a SentenceTransformer model.
1259
+
1260
+ Args:
1261
+ model_name_or_path (str): The name or path of the model.
1262
+ token (Optional[Union[bool, str]]): The token to be used for authentication. Defaults to None.
1263
+ cache_folder (Optional[str]): The folder to cache the model files. Defaults to None.
1264
+ revision (Optional[str]): The revision of the model. Defaults to None.
1265
+ local_files_only (bool): Whether to only use local files for the model. Defaults to False.
1266
+
1267
+ Returns:
1268
+ bool: True if the model is a SentenceTransformer model, False otherwise.
1269
+ """
1270
+ return bool(
1271
+ load_file_path(
1272
+ model_name_or_path,
1273
+ "modules.json",
1274
+ token,
1275
+ cache_folder,
1276
+ revision=revision,
1277
+ local_files_only=local_files_only,
1278
+ )
1279
+ )
1280
+
1281
+
1282
+ def load_file_path(
1283
+ model_name_or_path: str,
1284
+ filename: str,
1285
+ token: bool | str | None,
1286
+ cache_folder: str | None,
1287
+ revision: str | None = None,
1288
+ local_files_only: bool = False,
1289
+ ) -> str | None:
1290
+ """
1291
+ Loads a file from a local or remote location.
1292
+
1293
+ Args:
1294
+ model_name_or_path (str): The model name or path.
1295
+ filename (str): The name of the file to load.
1296
+ token (Optional[Union[bool, str]]): The token to access the remote file (if applicable).
1297
+ cache_folder (Optional[str]): The folder to cache the downloaded file (if applicable).
1298
+ revision (Optional[str], optional): The revision of the file (if applicable). Defaults to None.
1299
+ local_files_only (bool, optional): Whether to only consider local files. Defaults to False.
1300
+
1301
+ Returns:
1302
+ Optional[str]: The path to the loaded file, or None if the file could not be found or loaded.
1303
+ """
1304
+ # If file is local
1305
+ file_path = os.path.join(model_name_or_path, filename)
1306
+ if os.path.exists(file_path):
1307
+ return file_path
1308
+
1309
+ # If file is remote
1310
+ try:
1311
+ return hf_hub_download(
1312
+ model_name_or_path,
1313
+ filename=filename,
1314
+ revision=revision,
1315
+ library_name="sentence-transformers",
1316
+ token=token,
1317
+ cache_dir=cache_folder,
1318
+ local_files_only=local_files_only,
1319
+ )
1320
+ except Exception:
1321
+ return None
1322
+
1323
+
1324
+ def load_dir_path(
1325
+ model_name_or_path: str,
1326
+ directory: str,
1327
+ token: bool | str | None,
1328
+ cache_folder: str | None,
1329
+ revision: str | None = None,
1330
+ local_files_only: bool = False,
1331
+ ) -> str | None:
1332
+ """
1333
+ Loads the directory path for a given model name or path.
1334
+
1335
+ Args:
1336
+ model_name_or_path (str): The name or path of the model.
1337
+ directory (str): The directory to load.
1338
+ token (Optional[Union[bool, str]]): The token for authentication.
1339
+ cache_folder (Optional[str]): The folder to cache the downloaded files.
1340
+ revision (Optional[str], optional): The revision of the model. Defaults to None.
1341
+ local_files_only (bool, optional): Whether to only use local files. Defaults to False.
1342
+
1343
+ Returns:
1344
+ Optional[str]: The directory path if it exists, otherwise None.
1345
+ """
1346
+ # If file is local
1347
+ dir_path = os.path.join(model_name_or_path, directory)
1348
+ if os.path.exists(dir_path):
1349
+ return dir_path
1350
+
1351
+ download_kwargs = {
1352
+ "repo_id": model_name_or_path,
1353
+ "revision": revision,
1354
+ "allow_patterns": f"{directory}/**",
1355
+ "library_name": "sentence-transformers",
1356
+ "token": token,
1357
+ "cache_dir": cache_folder,
1358
+ "local_files_only": local_files_only,
1359
+ "tqdm_class": disabled_tqdm,
1360
+ }
1361
+ # Try to download from the remote
1362
+ try:
1363
+ repo_path = snapshot_download(**download_kwargs)
1364
+ except Exception:
1365
+ # Otherwise, try local (i.e. cache) only
1366
+ download_kwargs["local_files_only"] = True
1367
+ repo_path = snapshot_download(**download_kwargs)
1368
+ return os.path.join(repo_path, directory)
1369
+
1370
+
1371
+ def save_to_hub_args_decorator(func):
1372
+ @functools.wraps(func)
1373
+ def wrapper(self, *args, **kwargs):
1374
+ # If repo_id not already set, use repo_name
1375
+ repo_name = kwargs.pop("repo_name", None)
1376
+ if repo_name and "repo_id" not in kwargs:
1377
+ logger.warning(
1378
+ "Providing a `repo_name` keyword argument to `save_to_hub` is deprecated, please use `repo_id` instead."
1379
+ )
1380
+ kwargs["repo_id"] = repo_name
1381
+
1382
+ # If positional args are used, adjust for the new "token" keyword argument
1383
+ if len(args) >= 2:
1384
+ args = (*args[:2], None, *args[2:])
1385
+
1386
+ return func(self, *args, **kwargs)
1387
+
1388
+ return wrapper
1389
+
1390
+
1391
+ def get_device_name() -> Literal["mps", "cuda", "npu", "hpu", "cpu"]:
1392
+ """
1393
+ Returns the name of the device where this module is running on.
1394
+
1395
+ It's a simple implementation that doesn't cover cases when more powerful GPUs are available and
1396
+ not a primary device ('cuda:0') or MPS device is available, but not configured properly.
1397
+
1398
+ Returns:
1399
+ str: Device name, like 'cuda' or 'cpu'
1400
+ """
1401
+ if torch.cuda.is_available():
1402
+ return "cuda"
1403
+ elif torch.backends.mps.is_available():
1404
+ return "mps"
1405
+ elif is_torch_npu_available():
1406
+ return "npu"
1407
+ elif importlib.util.find_spec("habana_frameworks") is not None:
1408
+ import habana_frameworks.torch.hpu as hthpu
1409
+
1410
+ if hthpu.is_available():
1411
+ return "hpu"
1412
+ return "cpu"
1413
+
1414
+
1415
+ def check_package_availability(package_name: str, owner: str) -> bool:
1416
+ """
1417
+ Checks if a package is available from the correct owner.
1418
+ """
1419
+ try:
1420
+ meta = metadata(package_name)
1421
+ return meta["Name"] == package_name and owner in meta["Home-page"]
1422
+ except PackageNotFoundError:
1423
+ return False
1424
+
1425
+
1426
+ def is_accelerate_available() -> bool:
1427
+ """
1428
+ Returns True if the Huggingface accelerate library is available.
1429
+ """
1430
+ return check_package_availability("accelerate", "huggingface")
1431
+
1432
+
1433
+ def is_datasets_available() -> bool:
1434
+ """
1435
+ Returns True if the Huggingface datasets library is available.
1436
+ """
1437
+ return check_package_availability("datasets", "huggingface")
1438
+
1439
+
1440
+ def is_training_available() -> bool:
1441
+ """
1442
+ Returns True if we have the required dependencies for training Sentence
1443
+ Transformers models, i.e. Huggingface datasets and Huggingface accelerate.
1444
+ """
1445
+ return is_accelerate_available() and is_datasets_available()