Repository navigation
Expand file tree
/
Copy pathretrieval.py
More file actions
347 lines (285 loc) · 16.7 KB
/
Copy pathretrieval.py
File metadata and controls
347 lines (285 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
from __future__ import annotations
import heapq
import logging
from collections.abc import Callable
from itertools import islice
from operator import itemgetter
from typing import TYPE_CHECKING
import numpy as np
import torch
from torch import Tensor
from tqdm.autonotebook import tqdm
from .similarity import cos_sim, dot_score
from .tensor import _convert_to_batch_tensor, _convert_to_tensor, normalize_embeddings
logger = logging.getLogger(__name__)
if TYPE_CHECKING:
from sentence_transformers.sentence_transformer.model import SentenceTransformer
def paraphrase_mining(
model: SentenceTransformer,
sentences: list[str],
show_progress_bar: bool = False,
batch_size: int = 32,
query_chunk_size: int = 5000,
corpus_chunk_size: int = 100000,
max_pairs: int = 500000,
top_k: int = 100,
score_function: Callable[[Tensor, Tensor], Tensor] = cos_sim,
truncate_dim: int | None = None,
prompt_name: str | None = None,
prompt: str | None = None,
) -> list[list[float | int]]:
"""
Given a list of sentences / texts, this function performs paraphrase mining. It compares all sentences against all
other sentences and returns a list with the pairs that have the highest cosine similarity score.
Args:
model (SentenceTransformer): SentenceTransformer model for embedding computation
sentences (List[str]): A list of strings (texts or sentences)
show_progress_bar (bool, optional): Plotting of a progress bar. Defaults to False.
batch_size (int, optional): Number of texts that are encoded simultaneously by the model. Defaults to 32.
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.
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.
max_pairs (int, optional): Maximal number of text pairs returned. Defaults to 500000.
top_k (int, optional): For each sentence, we retrieve up to top_k other sentences. Defaults to 100.
score_function (Callable[[Tensor, Tensor], Tensor], optional): Function for computing scores. Assumed to be symmetric,
since only one direction's score is kept for each pair. By default, cosine similarity. Defaults to cos_sim.
truncate_dim (int, optional): The dimension to truncate sentence embeddings to. If None, uses the model's ones. Defaults to None.
prompt_name (Optional[str], optional): The name of a predefined prompt to use when encoding the sentence.
It must match a key in the model `prompts` dictionary, which can be set during model initialization
or loaded from the model configuration.
Ignored if `prompt` is provided. Defaults to None.
prompt (Optional[str], optional): A raw prompt string to prepend directly to the input sentence during encoding.
For instance, `prompt="query: "` transforms the sentence "What is the capital of France?" into:
"query: What is the capital of France?". Use this to override the prompt logic entirely and supply your own prefix.
This takes precedence over `prompt_name`. Defaults to None.
Returns:
List[List[Union[float, int]]]: Returns a list of triplets with the format [score, id1, id2]
"""
# Compute embedding for the sentences
embeddings = model.encode(
sentences,
show_progress_bar=show_progress_bar,
batch_size=batch_size,
convert_to_tensor=True,
truncate_dim=truncate_dim,
prompt_name=prompt_name,
prompt=prompt,
)
return paraphrase_mining_embeddings(
embeddings,
query_chunk_size=query_chunk_size,
corpus_chunk_size=corpus_chunk_size,
max_pairs=max_pairs,
top_k=top_k,
score_function=score_function,
)
def paraphrase_mining_embeddings(
embeddings: Tensor,
query_chunk_size: int = 5000,
corpus_chunk_size: int = 100000,
max_pairs: int = 500000,
top_k: int = 100,
score_function: Callable[[Tensor, Tensor], Tensor] = cos_sim,
) -> list[list[float | int]]:
"""
Given a list of sentences / texts, this function performs paraphrase mining. It compares all sentences against all
other sentences and returns a list with the pairs that have the highest cosine similarity score.
Args:
embeddings (Tensor): A tensor with the embeddings
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).
corpus_chunk_size (int): Compare a sentence simultaneously against #corpus_chunk_size other sentences. Decrease, to lower memory footprint (increases run-time).
max_pairs (int): Maximal number of text pairs returned.
top_k (int): For each sentence, we retrieve up to top_k other sentences
score_function (Callable[[Tensor, Tensor], Tensor]): Function for computing scores. Assumed to be symmetric,
since only one direction's score is kept for each pair. By default, cosine similarity.
Returns:
List[List[Union[float, int]]]: Returns a list of triplets with the format [score, id1, id2]
"""
# Mine for duplicates
pairs = [] # Min-heap of (score, i, j) with i < j, capped at max_pairs entries
queued_pairs = set() # The (i, j) of every pair currently in `pairs`
min_score = float("-inf")
for query_start_idx in range(0, len(embeddings), query_chunk_size):
query_embeddings = embeddings[query_start_idx : query_start_idx + query_chunk_size]
# Keep each query's top_k across all corpus chunks, so the candidates don't depend on corpus_chunk_size
scores_top_k_values, scores_top_k_idx = None, None
for corpus_start_idx in range(0, len(embeddings), corpus_chunk_size):
scores = score_function(
query_embeddings, embeddings[corpus_start_idx : corpus_start_idx + corpus_chunk_size]
).detach()
chunk_values, chunk_idx = torch.topk(scores, min(top_k + 1, len(scores[0])), dim=1, largest=True)
chunk_idx = chunk_idx + corpus_start_idx
if scores_top_k_values is None:
scores_top_k_values, scores_top_k_idx = chunk_values, chunk_idx
else:
values = torch.cat([scores_top_k_values, chunk_values], dim=1)
idx = torch.cat([scores_top_k_idx, chunk_idx], dim=1)
scores_top_k_values, top_pos = torch.topk(values, min(top_k + 1, len(values[0])), dim=1)
scores_top_k_idx = torch.gather(idx, 1, top_pos)
scores_top_k_values = scores_top_k_values.cpu().tolist()
scores_top_k_idx = scores_top_k_idx.cpu().tolist()
for query_itr in range(len(scores_top_k_values)):
i = query_start_idx + query_itr
neighbours = [
(j, score) for j, score in zip(scores_top_k_idx[query_itr], scores_top_k_values[query_itr]) if i != j
][:top_k]
for j, score in neighbours:
if score <= min_score:
continue
pair = (i, j) if i < j else (j, i)
if pair in queued_pairs:
continue
queued_pairs.add(pair)
if len(pairs) < max_pairs:
heapq.heappush(pairs, (score, *pair))
else:
evicted = heapq.heappushpop(pairs, (score, *pair))
queued_pairs.discard(evicted[1:])
min_score = evicted[0]
# Highest scores first
return sorted(([score, i, j] for score, i, j in pairs), key=lambda x: x[0], reverse=True)
def information_retrieval(*args, **kwargs) -> list[list[dict[str, int | float]]]:
"""This function is deprecated. Use semantic_search instead"""
return semantic_search(*args, **kwargs)
def semantic_search(
query_embeddings: Tensor,
corpus_embeddings: Tensor,
query_chunk_size: int = 100,
corpus_chunk_size: int = 500000,
top_k: int = 10,
score_function: Callable[[Tensor, Tensor], Tensor] = cos_sim,
) -> list[list[dict[str, int | float]]]:
"""
This function performs by default a cosine similarity search between a list of query embeddings and a list of corpus embeddings.
It can be used for Information Retrieval / Semantic Search for corpora up to about 1 Million entries.
Args:
query_embeddings (:class:`~torch.Tensor`): A 2 dimensional tensor with the query embeddings. Can be a sparse COO tensor.
corpus_embeddings (:class:`~torch.Tensor`): A 2 dimensional tensor with the corpus embeddings. Can be a sparse COO tensor.
query_chunk_size (int, optional): Process 100 queries simultaneously. Increasing that value increases the speed, but requires more memory. Defaults to 100.
corpus_chunk_size (int, optional): Scans the corpus 500k entries at a time. Increasing that value increases the speed, but requires more memory. Defaults to 500000.
top_k (int, optional): Retrieve top k matching entries. Defaults to 10.
score_function (Callable[[:class:`~torch.Tensor`, :class:`~torch.Tensor`], :class:`~torch.Tensor`], optional): Function for computing scores. By default, cosine similarity.
Returns:
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.
"""
query_embeddings = _convert_to_tensor(query_embeddings)
corpus_embeddings = _convert_to_tensor(corpus_embeddings)
if len(query_embeddings.shape) == 1:
query_embeddings = query_embeddings.unsqueeze(0)
# Check that corpus and queries are on the same device
if corpus_embeddings.device != query_embeddings.device:
query_embeddings = query_embeddings.to(corpus_embeddings.device)
queries_result_list = [[] for _ in range(len(query_embeddings))]
# cos_sim normalizes both of its inputs on every call, which would renormalize the same corpus chunk once per
# query chunk. Normalizing each corpus chunk once and taking the dot product computes the exact same scores.
normalize_chunks = score_function is cos_sim
# Iterate over chunks of the corpus. The corpus chunks are the outer loop so that each one is only prepared once,
# while every query still receives the corpus chunks in order.
for corpus_start_idx in range(0, len(corpus_embeddings), corpus_chunk_size):
corpus_end_idx = min(corpus_start_idx + corpus_chunk_size, len(corpus_embeddings))
if corpus_embeddings.is_sparse:
indices = torch.arange(corpus_start_idx, corpus_end_idx, device=corpus_embeddings.device)
corpus_chunk = corpus_embeddings.index_select(0, indices)
else:
corpus_chunk = corpus_embeddings[corpus_start_idx:corpus_end_idx]
if normalize_chunks:
corpus_chunk = normalize_embeddings(_convert_to_batch_tensor(corpus_chunk))
for query_start_idx in range(0, len(query_embeddings), query_chunk_size):
query_end_idx = min(query_start_idx + query_chunk_size, len(query_embeddings))
if query_embeddings.is_sparse:
indices = torch.arange(query_start_idx, query_end_idx, device=query_embeddings.device)
query_chunk = query_embeddings.index_select(0, indices)
else:
query_chunk = query_embeddings[query_start_idx:query_end_idx]
# Compute cosine similarities
if normalize_chunks:
cos_scores = dot_score(normalize_embeddings(_convert_to_batch_tensor(query_chunk)), corpus_chunk)
else:
cos_scores = score_function(query_chunk, corpus_chunk)
# Get top-k scores
cos_scores_top_k_values, cos_scores_top_k_idx = torch.topk(
cos_scores, min(top_k, len(cos_scores[0])), dim=1, largest=True, sorted=False
)
cos_scores_top_k_values = cos_scores_top_k_values.cpu().tolist()
cos_scores_top_k_idx = (cos_scores_top_k_idx + corpus_start_idx).cpu().tolist()
for query_results, corpus_ids, scores in zip(
queries_result_list[query_start_idx:query_end_idx], cos_scores_top_k_idx, cos_scores_top_k_values
):
# The heap tracks the quantity of the first element in the tuple. Fill it up to top_k, then only
# keep a new candidate if it beats the current minimum.
candidates = zip(scores, corpus_ids)
for candidate in islice(candidates, top_k - len(query_results)):
heapq.heappush(query_results, candidate)
for candidate in candidates:
heapq.heappushpop(query_results, candidate)
for query_id, query_results in enumerate(queries_result_list):
queries_result_list[query_id] = [
{"corpus_id": corpus_id, "score": score}
for score, corpus_id in sorted(query_results, key=itemgetter(0), reverse=True)
]
return queries_result_list
def community_detection(
embeddings: torch.Tensor | np.ndarray,
threshold: float = 0.75,
min_community_size: int = 10,
batch_size: int = 1024,
show_progress_bar: bool = False,
) -> list[list[int]]:
"""
Function for Fast Community Detection.
Finds communities of embeddings whose cosine similarity to a central point is at least threshold.
Returns only communities that are larger than min_community_size. The communities are returned
in decreasing order. The first element in each list is the central point in the community.
Args:
embeddings (torch.Tensor or numpy.ndarray): The input embeddings.
threshold (float): The threshold for determining if two embeddings are close. Defaults to 0.75.
min_community_size (int): The minimum size of a community to be considered. Defaults to 10.
batch_size (int): The batch size for computing cosine similarity scores. Defaults to 1024.
show_progress_bar (bool): Whether to show a progress bar during computation. Defaults to False.
Returns:
List[List[int]]: A list of communities, where each community is represented as a list of indices.
"""
if len(embeddings) == 0:
return []
embeddings = _convert_to_tensor(embeddings)
if embeddings.ndim == 1:
embeddings = embeddings.unsqueeze(0)
if len(embeddings) < min_community_size:
return []
threshold = torch.tensor(threshold, device=embeddings.device)
embeddings = normalize_embeddings(embeddings)
extracted_communities = []
# Maximum size for community
sort_max_size = min(max(2 * min_community_size, 50), len(embeddings))
for start_idx in tqdm(
range(0, len(embeddings), batch_size), desc="Finding clusters", disable=not show_progress_bar
):
# Compute cosine similarity scores
cos_scores = embeddings[start_idx : start_idx + batch_size] @ embeddings.T
top_k_values, _ = cos_scores.topk(k=min_community_size, largest=True)
large_enough_mask = top_k_values[:, -1] >= threshold
if not large_enough_mask.any():
continue
cos_scores = cos_scores[large_enough_mask]
top_k_values, top_k_indices = cos_scores.topk(k=sort_max_size, largest=True)
while sort_max_size < len(embeddings) and (top_k_values[:, -1] >= threshold).any():
sort_max_size = min(2 * sort_max_size, len(embeddings))
top_k_values, top_k_indices = cos_scores.topk(k=sort_max_size, largest=True)
row_wise_count = (top_k_values >= threshold).sum(1)
top_k_indices = top_k_indices.cpu()
centers = (large_enough_mask.nonzero(as_tuple=True)[0] + start_idx).tolist()
for center, count, indices in zip(centers, row_wise_count.tolist(), top_k_indices):
extracted_communities.append((center, indices[:count].numpy().astype(np.uint32)))
# Largest cluster first
extracted_communities = sorted(extracted_communities, key=lambda x: len(x[1]), reverse=True)
# Step 2) Remove overlapping communities using a dense boolean mask of already claimed indices
unique_communities = []
used = np.zeros(len(embeddings), dtype=bool)
for center, community in extracted_communities:
if used[center]:
continue
non_overlapped_community = community[~used[community]]
if len(non_overlapped_community) >= min_community_size:
unique_community = [center] + non_overlapped_community[non_overlapped_community != center].tolist()
unique_communities.append(unique_community)
used[unique_community] = True
return sorted(unique_communities, key=len, reverse=True)