semhash 0.3.2__tar.gz → 0.4.0__tar.gz
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.
- {semhash-0.3.2 → semhash-0.4.0}/.github/workflows/ci.yaml +1 -3
- {semhash-0.3.2 → semhash-0.4.0}/.pre-commit-config.yaml +5 -2
- semhash-0.4.0/CITATION.cff +27 -0
- {semhash-0.3.2 → semhash-0.4.0}/Makefile +9 -1
- {semhash-0.3.2 → semhash-0.4.0}/PKG-INFO +224 -125
- {semhash-0.3.2 → semhash-0.4.0}/README.md +220 -121
- semhash-0.4.0/benchmarks/README.md +163 -0
- {semhash-0.3.2 → semhash-0.4.0}/benchmarks/data.py +6 -0
- semhash-0.4.0/benchmarks/results/image_train_benchmark_results.json +20 -0
- semhash-0.4.0/benchmarks/results/image_train_test_benchmark_results.json +22 -0
- semhash-0.4.0/benchmarks/run_image_benchmarks.py +194 -0
- semhash-0.3.2/benchmarks/run_benchmarks.py → semhash-0.4.0/benchmarks/run_text_benchmarks.py +1 -1
- {semhash-0.3.2 → semhash-0.4.0}/pyproject.toml +4 -3
- semhash-0.4.0/semhash/__init__.py +5 -0
- {semhash-0.3.2 → semhash-0.4.0}/semhash/datamodels.py +19 -32
- semhash-0.4.0/semhash/records.py +167 -0
- {semhash-0.3.2 → semhash-0.4.0}/semhash/semhash.py +165 -208
- semhash-0.4.0/semhash/utils.py +149 -0
- semhash-0.4.0/semhash/version.py +2 -0
- {semhash-0.3.2 → semhash-0.4.0}/semhash.egg-info/PKG-INFO +224 -125
- {semhash-0.3.2 → semhash-0.4.0}/semhash.egg-info/SOURCES.txt +7 -1
- {semhash-0.3.2 → semhash-0.4.0}/semhash.egg-info/requires.txt +1 -0
- {semhash-0.3.2 → semhash-0.4.0}/tests/conftest.py +0 -6
- {semhash-0.3.2 → semhash-0.4.0}/tests/test_datamodels.py +64 -44
- semhash-0.4.0/tests/test_semhash.py +328 -0
- semhash-0.4.0/tests/test_utils.py +167 -0
- {semhash-0.3.2 → semhash-0.4.0}/uv.lock +17 -154
- semhash-0.3.2/semhash/__init__.py +0 -3
- semhash-0.3.2/semhash/records.py +0 -39
- semhash-0.3.2/semhash/utils.py +0 -55
- semhash-0.3.2/semhash/version.py +0 -2
- semhash-0.3.2/tests/test_semhash.py +0 -218
- {semhash-0.3.2 → semhash-0.4.0}/.gitignore +0 -0
- {semhash-0.3.2 → semhash-0.4.0}/LICENSE +0 -0
- {semhash-0.3.2 → semhash-0.4.0}/assets/images/semhash_logo.png +0 -0
- {semhash-0.3.2 → semhash-0.4.0}/assets/images/semhash_logo_v2.png +0 -0
- {semhash-0.3.2 → semhash-0.4.0}/benchmarks/__init__.py +0 -0
- {semhash-0.3.2 → semhash-0.4.0}/benchmarks/results/train_benchmark_results.json +0 -0
- {semhash-0.3.2 → semhash-0.4.0}/benchmarks/results/train_test_benchmark_results.json +0 -0
- {semhash-0.3.2 → semhash-0.4.0}/semhash/index.py +0 -0
- {semhash-0.3.2 → semhash-0.4.0}/semhash.egg-info/dependency_links.txt +0 -0
- {semhash-0.3.2 → semhash-0.4.0}/semhash.egg-info/top_level.txt +0 -0
- {semhash-0.3.2 → semhash-0.4.0}/setup.cfg +0 -0
- {semhash-0.3.2 → semhash-0.4.0}/tests/data/test_model/README.md +0 -0
- {semhash-0.3.2 → semhash-0.4.0}/tests/data/test_model/config.json +0 -0
- {semhash-0.3.2 → semhash-0.4.0}/tests/data/test_model/model.safetensors +0 -0
- {semhash-0.3.2 → semhash-0.4.0}/tests/data/test_model/modules.json +0 -0
- {semhash-0.3.2 → semhash-0.4.0}/tests/data/test_model/tokenizer.json +0 -0
|
@@ -10,10 +10,8 @@ jobs:
|
|
|
10
10
|
strategy:
|
|
11
11
|
matrix:
|
|
12
12
|
os: ["ubuntu-latest", "windows-latest"]
|
|
13
|
-
python-version: ["3.
|
|
13
|
+
python-version: ["3.10", "3.11", "3.12"]
|
|
14
14
|
exclude:
|
|
15
|
-
- os: windows-latest
|
|
16
|
-
python-version: "3.9"
|
|
17
15
|
- os: windows-latest
|
|
18
16
|
python-version: "3.11"
|
|
19
17
|
- os: windows-latest
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
cff-version: 1.2.0
|
|
2
|
+
message: "If you use SemHash in your research, please cite it as below."
|
|
3
|
+
title: "SemHash: Fast Multimodal Semantic Deduplication & Filtering"
|
|
4
|
+
authors:
|
|
5
|
+
- family-names: "van Dongen"
|
|
6
|
+
given-names: "Thomas"
|
|
7
|
+
- family-names: "Tulkens"
|
|
8
|
+
given-names: "Stephan"
|
|
9
|
+
doi: 10.5281/zenodo.17265942
|
|
10
|
+
license: MIT
|
|
11
|
+
url: "https://github.com/MinishLab/semhash"
|
|
12
|
+
repository-code: "https://github.com/MinishLab/semhash"
|
|
13
|
+
date-released: "2025-01-05"
|
|
14
|
+
|
|
15
|
+
preferred-citation:
|
|
16
|
+
type: software
|
|
17
|
+
title: "SemHash: Fast Multimodal Semantic Deduplication & Filtering"
|
|
18
|
+
authors:
|
|
19
|
+
- family-names: "van Dongen"
|
|
20
|
+
given-names: "Thomas"
|
|
21
|
+
- family-names: "Tulkens"
|
|
22
|
+
given-names: "Stephan"
|
|
23
|
+
year: 2025
|
|
24
|
+
publisher: Zenodo
|
|
25
|
+
doi: 10.5281/zenodo.17265942
|
|
26
|
+
url: "https://github.com/MinishLab/semhash"
|
|
27
|
+
license: MIT
|
|
@@ -9,10 +9,18 @@ install: venv
|
|
|
9
9
|
uv run pre-commit install
|
|
10
10
|
|
|
11
11
|
install-no-pre-commit:
|
|
12
|
-
uv pip install ".[dev]"
|
|
12
|
+
uv pip install ".[dev,all]"
|
|
13
13
|
|
|
14
14
|
fix:
|
|
15
15
|
uv run pre-commit run --all-files
|
|
16
16
|
|
|
17
17
|
test:
|
|
18
18
|
uv run pytest --cov=semhash --cov-report=term-missing
|
|
19
|
+
|
|
20
|
+
benchmark-text:
|
|
21
|
+
uv run python -m benchmarks.run_text_benchmarks
|
|
22
|
+
|
|
23
|
+
benchmark-image:
|
|
24
|
+
uv run python -m benchmarks.run_image_benchmarks
|
|
25
|
+
|
|
26
|
+
benchmark: benchmark-text benchmark-image
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: semhash
|
|
3
|
-
Version: 0.
|
|
4
|
-
Summary: Fast Semantic
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: Fast Multimodal Semantic Deduplication & Filtering
|
|
5
5
|
Author-email: Thomas van Dongen <thomas123@live.nl>, Stéphan Tulkens <stephantul@gmail.com>
|
|
6
6
|
License: MIT License
|
|
7
7
|
|
|
@@ -35,16 +35,16 @@ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
|
35
35
|
Classifier: Topic :: Software Development :: Libraries
|
|
36
36
|
Classifier: License :: OSI Approved :: MIT License
|
|
37
37
|
Classifier: Programming Language :: Python :: 3 :: Only
|
|
38
|
-
Classifier: Programming Language :: Python :: 3.9
|
|
39
38
|
Classifier: Programming Language :: Python :: 3.10
|
|
40
39
|
Classifier: Programming Language :: Python :: 3.11
|
|
41
40
|
Classifier: Programming Language :: Python :: 3.12
|
|
42
41
|
Classifier: Natural Language :: English
|
|
43
|
-
Requires-Python: >=3.
|
|
42
|
+
Requires-Python: >=3.10
|
|
44
43
|
Description-Content-Type: text/markdown
|
|
45
44
|
Requires-Dist: model2vec>=0.3.4
|
|
46
45
|
Requires-Dist: vicinity[usearch]>=0.4.3
|
|
47
46
|
Requires-Dist: frozendict
|
|
47
|
+
Requires-Dist: pyversity
|
|
48
48
|
Provides-Extra: dev
|
|
49
49
|
Requires-Dist: black; extra == "dev"
|
|
50
50
|
Requires-Dist: ipython; extra == "dev"
|
|
@@ -58,7 +58,7 @@ Requires-Dist: ruff; extra == "dev"
|
|
|
58
58
|
|
|
59
59
|
<h2 align="center">
|
|
60
60
|
<img width="30%" alt="SemHash logo" src="assets/images/semhash_logo_v2.png"><br/>
|
|
61
|
-
Fast Semantic
|
|
61
|
+
Fast Multimodal Semantic Deduplication & Filtering
|
|
62
62
|
</h2>
|
|
63
63
|
|
|
64
64
|
|
|
@@ -94,9 +94,9 @@ Requires-Dist: ruff; extra == "dev"
|
|
|
94
94
|
</div>
|
|
95
95
|
|
|
96
96
|
|
|
97
|
-
SemHash is a lightweight
|
|
97
|
+
SemHash is a lightweight, multimodal library for semantic deduplication, outlier filtering, and representative sample selection. Text works out of the box with fast [Model2Vec](https://github.com/MinishLab/model2vec) embeddings, and images, audio, and other modalities are supported with custom encoders.
|
|
98
98
|
|
|
99
|
-
SemHash supports both single-dataset
|
|
99
|
+
SemHash supports both single-dataset operations (clean a training set) and cross-dataset operations (deduplicate test against train). It works with simple lists and complex multi-column datasets, and includes inspection tools to help you understand and refine results. All operations use [Vicinity](https://github.com/MinishLab/vicinity) for efficient similarity search.
|
|
100
100
|
|
|
101
101
|
## Quickstart
|
|
102
102
|
|
|
@@ -105,6 +105,8 @@ Install the package with:
|
|
|
105
105
|
pip install semhash
|
|
106
106
|
```
|
|
107
107
|
|
|
108
|
+
### Text Deduplication, Filtering & Representative Sampling
|
|
109
|
+
|
|
108
110
|
Deduplicate a single dataset, filter outliers, and find representative samples with the following code (note: the examples assume you have `datasets` installed, which you can install with `pip install datasets`):
|
|
109
111
|
|
|
110
112
|
```python
|
|
@@ -127,7 +129,35 @@ filtered_texts = semhash.self_filter_outliers().selected
|
|
|
127
129
|
representative_texts = semhash.self_find_representative().selected
|
|
128
130
|
```
|
|
129
131
|
|
|
130
|
-
|
|
132
|
+
### Image Deduplication, Filtering & Representative Sampling
|
|
133
|
+
|
|
134
|
+
Deduplicate an image dataset, filter outliers, and find representative samples using a vision model (requires `pip install sentence-transformers`):
|
|
135
|
+
|
|
136
|
+
```python
|
|
137
|
+
from datasets import load_dataset
|
|
138
|
+
from sentence_transformers import SentenceTransformer
|
|
139
|
+
from semhash import SemHash
|
|
140
|
+
|
|
141
|
+
# Load an image dataset and vision model
|
|
142
|
+
model = SentenceTransformer('clip-ViT-B-32')
|
|
143
|
+
dataset = load_dataset("uoft-cs/cifar10", split="test")
|
|
144
|
+
|
|
145
|
+
# Initialize a SemHash instance with the 'img' column
|
|
146
|
+
semhash = SemHash.from_records(list(dataset), columns=["img"], model=model)
|
|
147
|
+
|
|
148
|
+
# Deduplicate the images
|
|
149
|
+
deduplicated_images = semhash.self_deduplicate().selected
|
|
150
|
+
|
|
151
|
+
# Filter outliers
|
|
152
|
+
filtered_images = semhash.self_filter_outliers().selected
|
|
153
|
+
|
|
154
|
+
# Find representative images
|
|
155
|
+
representative_images = semhash.self_find_representative().selected
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### Cross-Dataset Deduplication, Filtering & Representative Sampling
|
|
159
|
+
|
|
160
|
+
Deduplicate across two datasets, filter outliers, and find representative samples (e.g., eliminating train/test leakage):
|
|
131
161
|
|
|
132
162
|
```python
|
|
133
163
|
from datasets import load_dataset
|
|
@@ -149,13 +179,12 @@ filtered_test_texts = semhash.filter_outliers(records=test_texts, outlier_percen
|
|
|
149
179
|
|
|
150
180
|
# Find representative texts in the test data against the training data,
|
|
151
181
|
# optionally with a specific selection size
|
|
152
|
-
representative_test_texts = semhash.find_representative(
|
|
153
|
-
records=test_texts, selection_size=10).selected
|
|
154
|
-
|
|
155
|
-
|
|
182
|
+
representative_test_texts = semhash.find_representative(records=test_texts, selection_size=10).selected
|
|
156
183
|
```
|
|
157
184
|
|
|
158
|
-
|
|
185
|
+
### Multi-Column Deduplication
|
|
186
|
+
|
|
187
|
+
Deduplicate multi-column datasets (e.g., deduplicating a QA dataset):
|
|
159
188
|
|
|
160
189
|
```python
|
|
161
190
|
from datasets import load_dataset
|
|
@@ -172,19 +201,47 @@ semhash = SemHash.from_records(records=records, columns=["question", "context"])
|
|
|
172
201
|
|
|
173
202
|
# Deduplicate the records
|
|
174
203
|
deduplicated_records = semhash.self_deduplicate().selected
|
|
175
|
-
|
|
176
|
-
# Filter outliers from the records
|
|
177
|
-
filtered_texts = semhash.self_filter_outliers().selected
|
|
178
|
-
|
|
179
|
-
# Find representative texts in the records
|
|
180
|
-
representative_texts = semhash.self_find_representative().selected
|
|
181
204
|
```
|
|
182
205
|
|
|
183
|
-
The `deduplicate` and `self_deduplicate` functions return a [DeduplicationResult](https://github.com/MinishLab/semhash/blob/main/semhash/datamodels.py#
|
|
206
|
+
The `deduplicate` and `self_deduplicate` functions return a [DeduplicationResult](https://github.com/MinishLab/semhash/blob/main/semhash/datamodels.py#L58). This object stores the deduplicated corpus, a set of duplicate objects (along with the objects that caused duplication), and several useful functions to further inspect the deduplication result.
|
|
184
207
|
|
|
185
|
-
The `filter_outliers`, `self_filter_outliers`, `find_representative`, and `self_find_representative` functions return a [FilterResult](https://github.com/MinishLab/semhash/blob/main/semhash/datamodels.py#
|
|
208
|
+
The `filter_outliers`, `self_filter_outliers`, `find_representative`, and `self_find_representative` functions return a [FilterResult](https://github.com/MinishLab/semhash/blob/main/semhash/datamodels.py#179). This object stores the found outliers/representative samples.
|
|
186
209
|
|
|
187
210
|
For both the `DeduplicationResult` and `FilterResult` objects, you can easily view the filtered records with the `selected` attribute (e.g. to view outliers: `outliers = semhash.self_filter_outliers().filtered`)
|
|
211
|
+
|
|
212
|
+
### Inspecting Deduplication Results
|
|
213
|
+
|
|
214
|
+
The `DeduplicationResult` object provides powerful tools for understanding and refining your deduplication:
|
|
215
|
+
|
|
216
|
+
```python
|
|
217
|
+
from datasets import load_dataset
|
|
218
|
+
from semhash import SemHash
|
|
219
|
+
|
|
220
|
+
# Load and deduplicate a dataset
|
|
221
|
+
texts = load_dataset("ag_news", split="train")["text"]
|
|
222
|
+
semhash = SemHash.from_records(records=texts)
|
|
223
|
+
result = semhash.self_deduplicate()
|
|
224
|
+
|
|
225
|
+
# Access deduplicated and duplicate records
|
|
226
|
+
deduplicated_texts = result.selected
|
|
227
|
+
duplicate_texts = result.filtered
|
|
228
|
+
|
|
229
|
+
# View deduplication statistics
|
|
230
|
+
print(f"Duplicate ratio: {result.duplicate_ratio}")
|
|
231
|
+
print(f"Exact duplicate ratio: {result.exact_duplicate_ratio}")
|
|
232
|
+
|
|
233
|
+
# Find edge cases to tune your threshold
|
|
234
|
+
least_similar = result.get_least_similar_from_duplicates(n=5)
|
|
235
|
+
|
|
236
|
+
# Adjust threshold without re-deduplicating
|
|
237
|
+
result.rethreshold(0.95)
|
|
238
|
+
|
|
239
|
+
# View each kept record with its duplicate cluster
|
|
240
|
+
for item in result.selected_with_duplicates:
|
|
241
|
+
print(f"Kept: {item.record}")
|
|
242
|
+
print(f"Duplicates: {item.duplicates}") # List of (duplicate_text, similarity_score)
|
|
243
|
+
```
|
|
244
|
+
|
|
188
245
|
## Main Features
|
|
189
246
|
|
|
190
247
|
- **Fast**: SemHash uses [model2vec](https://github.com/MinishLab/model2vec) to embed texts and [vicinity](https://github.com/MinishLab/vicinity) to perform similarity search, making it extremely fast.
|
|
@@ -234,14 +291,11 @@ The following code snippet shows how to deduplicate across two datasets, filter
|
|
|
234
291
|
from datasets import load_dataset
|
|
235
292
|
from semhash import SemHash
|
|
236
293
|
|
|
237
|
-
# Initialize a SemHash instance
|
|
238
|
-
semhash = SemHash()
|
|
239
|
-
|
|
240
294
|
# Load two datasets to deduplicate
|
|
241
295
|
train_texts = load_dataset("ag_news", split="train")["text"]
|
|
242
296
|
test_texts = load_dataset("ag_news", split="test")["text"]
|
|
243
297
|
|
|
244
|
-
# Initialize a SemHash instance
|
|
298
|
+
# Initialize a SemHash instance with the training data
|
|
245
299
|
semhash = SemHash.from_records(records=train_texts)
|
|
246
300
|
|
|
247
301
|
# Deduplicate the test data against the training data
|
|
@@ -288,44 +342,67 @@ representative_records = semhash.self_find_representative().selected
|
|
|
288
342
|
</details>
|
|
289
343
|
|
|
290
344
|
<details>
|
|
291
|
-
<summary>
|
|
345
|
+
<summary> Deduplicate, filter outliers, and find representative samples on image datasets </summary>
|
|
292
346
|
<br>
|
|
293
347
|
|
|
294
|
-
|
|
348
|
+
You can bring your own encoder for any modality by implementing the Encoder protocol. Here's an example using a vision model from timm for image deduplication:
|
|
295
349
|
|
|
296
350
|
```python
|
|
297
351
|
from datasets import load_dataset
|
|
352
|
+
import timm
|
|
353
|
+
import torch
|
|
298
354
|
from semhash import SemHash
|
|
299
355
|
|
|
300
|
-
#
|
|
301
|
-
texts = load_dataset("ag_news", split="train")["text"]
|
|
356
|
+
# Requires: pip install timm torch datasets
|
|
302
357
|
|
|
303
|
-
#
|
|
304
|
-
|
|
358
|
+
# Create a custom image encoder
|
|
359
|
+
class VisionEncoder:
|
|
360
|
+
"""Custom encoder using timm models. Implements the Encoder protocol."""
|
|
305
361
|
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
#
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
#
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
362
|
+
def __init__(self, model_name: str = "mobilenetv3_small_100.lamb_in1k"):
|
|
363
|
+
self.model = timm.create_model(model_name, pretrained=True, num_classes=0).eval()
|
|
364
|
+
data_config = timm.data.resolve_model_data_config(self.model)
|
|
365
|
+
self.transform = timm.data.create_transform(**data_config, is_training=False)
|
|
366
|
+
|
|
367
|
+
def encode(self, inputs, batch_size: int = 128):
|
|
368
|
+
"""Encode a batch of PIL images into embeddings."""
|
|
369
|
+
import numpy as np
|
|
370
|
+
|
|
371
|
+
# Convert grayscale to RGB if needed
|
|
372
|
+
rgb_inputs = [img.convert("RGB") if img.mode != "RGB" else img for img in inputs]
|
|
373
|
+
|
|
374
|
+
# Process in batches to avoid memory issues
|
|
375
|
+
all_embeddings = []
|
|
376
|
+
with torch.no_grad():
|
|
377
|
+
for i in range(0, len(rgb_inputs), batch_size):
|
|
378
|
+
batch_inputs = rgb_inputs[i : i + batch_size]
|
|
379
|
+
batch = torch.stack([self.transform(img) for img in batch_inputs])
|
|
380
|
+
embeddings = self.model(batch).numpy()
|
|
381
|
+
all_embeddings.append(embeddings)
|
|
382
|
+
|
|
383
|
+
return np.vstack(all_embeddings)
|
|
384
|
+
|
|
385
|
+
# Load image dataset
|
|
386
|
+
dataset = load_dataset("uoft-cs/cifar10", split="test")
|
|
387
|
+
train_data = [{"img": img, "id": i} for i, img in enumerate(dataset["img"][:100])]
|
|
388
|
+
test_data = [{"img": img, "id": i} for i, img in enumerate(dataset["img"][100:150])]
|
|
389
|
+
|
|
390
|
+
# Initialize SemHash with the custom vision encoder
|
|
391
|
+
semhash = SemHash.from_records(train_data, columns=["img"], model=VisionEncoder())
|
|
392
|
+
|
|
393
|
+
# Single-dataset operations
|
|
394
|
+
deduplicated = semhash.self_deduplicate().selected
|
|
395
|
+
outliers = semhash.self_filter_outliers().selected
|
|
396
|
+
representatives = semhash.self_find_representative().selected
|
|
397
|
+
|
|
398
|
+
# Cross-dataset operations
|
|
399
|
+
test_deduplicated = semhash.deduplicate(test_data).selected
|
|
400
|
+
test_outliers = semhash.filter_outliers(test_data).selected
|
|
401
|
+
test_representatives = semhash.find_representative(test_data, selection_size=10).selected
|
|
327
402
|
```
|
|
328
403
|
|
|
404
|
+
The Encoder protocol requires only an `encode(inputs, **kwargs)` method that returns a numpy array. This makes it easy to integrate any embedding model for any modality.
|
|
405
|
+
|
|
329
406
|
</details>
|
|
330
407
|
|
|
331
408
|
<details>
|
|
@@ -343,7 +420,7 @@ from semhash import SemHash
|
|
|
343
420
|
texts = load_dataset("ag_news", split="train")["text"]
|
|
344
421
|
|
|
345
422
|
# Load an embedding model (in this example, a multilingual model)
|
|
346
|
-
model = StaticModel.from_pretrained("minishlab/
|
|
423
|
+
model = StaticModel.from_pretrained("minishlab/potion-multilingual-128M")
|
|
347
424
|
|
|
348
425
|
# Initialize a SemHash with the model and custom encoder
|
|
349
426
|
semhash = SemHash.from_records(records=texts, model=model)
|
|
@@ -381,21 +458,23 @@ deduplicated_texts = semhash.self_deduplicate()
|
|
|
381
458
|
<summary> Using custom ANN backends </summary>
|
|
382
459
|
<br>
|
|
383
460
|
|
|
384
|
-
|
|
461
|
+
By default, we use [USearch](https://github.com/unum-cloud/USearch) as the ANN (approximate-nearest neighbors) backend for deduplication. We recommend keeping this since the recall for smaller datasets is ~100%, and it's needed for larger datasets (>1M samples) since these will take too long to deduplicate without ANN. If you want to use a flat/exact-matching backend, you can set `ann_backend=Backend.BASIC` in the SemHash constructor:
|
|
385
462
|
|
|
386
463
|
```python
|
|
387
|
-
from datasets import load_dataset
|
|
388
464
|
from semhash import SemHash
|
|
389
465
|
from vicinity import Backend
|
|
390
466
|
|
|
391
|
-
|
|
392
|
-
|
|
467
|
+
semhash = SemHash.from_records(records=texts, ann_backend=Backend.BASIC)
|
|
468
|
+
```
|
|
393
469
|
|
|
394
|
-
|
|
395
|
-
semhash = SemHash.from_records(records=texts, ann_backend=Backend.FAISS, nlist=50)
|
|
470
|
+
Any backend from [Vicinity](https://github.com/MinishLab/vicinity) can be used with SemHash. The following code snippet shows how to use [FAISS](https://github.com/facebookresearch/faiss) with a custom `nlist` parameter:
|
|
396
471
|
|
|
397
|
-
|
|
398
|
-
|
|
472
|
+
```python
|
|
473
|
+
from datasets import load_dataset
|
|
474
|
+
from semhash import SemHash
|
|
475
|
+
from vicinity import Backend
|
|
476
|
+
|
|
477
|
+
semhash = SemHash.from_records(records=texts, ann_backend=Backend.FAISS, nlist=50)
|
|
399
478
|
```
|
|
400
479
|
|
|
401
480
|
For the full list of supported ANN backends and args, see the [Vicinity docs](https://github.com/MinishLab/vicinity/tree/main?tab=readme-ov-file#supported-backends).
|
|
@@ -432,77 +511,94 @@ deduplicated_dataframe = pd.DataFrame(deduplicated_records)
|
|
|
432
511
|
|
|
433
512
|
</details>
|
|
434
513
|
|
|
435
|
-
|
|
514
|
+
<details>
|
|
515
|
+
<summary> Initializing from embeddings </summary>
|
|
516
|
+
<br>
|
|
517
|
+
You can also initialize SemHash from pre-computed embeddings. The following code snippet shows how to do this:
|
|
436
518
|
|
|
437
519
|
```python
|
|
438
|
-
|
|
520
|
+
from datasets import load_dataset
|
|
521
|
+
from model2vec import StaticModel
|
|
522
|
+
from semhash import SemHash
|
|
523
|
+
|
|
524
|
+
# Load a dataset
|
|
525
|
+
texts = load_dataset("ag_news", split="train")["text"]
|
|
526
|
+
|
|
527
|
+
# Load an embedding model
|
|
528
|
+
model = StaticModel.from_pretrained("minishlab/potion-base-8M")
|
|
529
|
+
|
|
530
|
+
# Create embeddings
|
|
531
|
+
embeddings = model.encode(texts)
|
|
532
|
+
|
|
533
|
+
# Initialize SemHash from embeddings
|
|
534
|
+
semhash = SemHash.from_embeddings(embeddings=embeddings, records=texts, model=model)
|
|
535
|
+
|
|
536
|
+
# Deduplicate, filter outliers, and find representative samples
|
|
537
|
+
deduplicated_texts = semhash.self_deduplicate().selected
|
|
538
|
+
filtered_texts = semhash.self_filter_outliers().selected
|
|
539
|
+
representative_texts = semhash.self_find_representative().selected
|
|
439
540
|
```
|
|
541
|
+
</details>
|
|
542
|
+
|
|
543
|
+
<details>
|
|
544
|
+
<summary> Initializing from a HuggingFace Dataset </summary>
|
|
545
|
+
<br>
|
|
546
|
+
You can easily use SemHash with HuggingFace Datasets by converting them to a list:
|
|
547
|
+
|
|
548
|
+
```python
|
|
549
|
+
from datasets import load_dataset
|
|
550
|
+
from semhash import SemHash
|
|
551
|
+
|
|
552
|
+
# Load a HuggingFace dataset
|
|
553
|
+
dataset = load_dataset("ag_news", split="train")
|
|
554
|
+
|
|
555
|
+
# Convert to list and initialize SemHash
|
|
556
|
+
semhash = SemHash.from_records(records=list(dataset), columns=["text"])
|
|
557
|
+
|
|
558
|
+
# Deduplicate, filter outliers, and find representative samples
|
|
559
|
+
deduplicated_texts = semhash.self_deduplicate().selected
|
|
560
|
+
filtered_texts = semhash.self_filter_outliers().selected
|
|
561
|
+
representative_texts = semhash.self_find_representative().selected
|
|
562
|
+
```
|
|
563
|
+
|
|
564
|
+
This also works with multi-column datasets:
|
|
565
|
+
|
|
566
|
+
```python
|
|
567
|
+
from datasets import load_dataset
|
|
568
|
+
from semhash import SemHash
|
|
569
|
+
|
|
570
|
+
# Load a multi-column dataset
|
|
571
|
+
dataset = load_dataset("squad_v2", split="train")
|
|
572
|
+
|
|
573
|
+
# Convert to list and initialize with multiple columns
|
|
574
|
+
semhash = SemHash.from_records(records=list(dataset), columns=["question", "context"])
|
|
575
|
+
|
|
576
|
+
# Deduplicate the records
|
|
577
|
+
deduplicated_records = semhash.self_deduplicate().selected
|
|
578
|
+
```
|
|
579
|
+
</details>
|
|
580
|
+
|
|
440
581
|
|
|
441
582
|
|
|
442
583
|
|
|
443
584
|
## Benchmarks
|
|
444
585
|
|
|
445
|
-
We've benchmarked
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
### Train Deduplication Benchmark
|
|
451
|
-
|
|
452
|
-
| Dataset | Original Train Size | Deduplicated Train Size | % Removed | Deduplication Time (s) |
|
|
453
|
-
|----------------------|----------------------|--------------------------|------------|--------------------------|
|
|
454
|
-
| bbc | 1225 | 1144 | 6.61 | 0.57 |
|
|
455
|
-
| senteval_cr | 3012 | 2990 | 0.73 | 0.14 |
|
|
456
|
-
| tweet_sentiment_extraction | 27481 | 26695 | 2.86 | 1.77 |
|
|
457
|
-
| emotion | 16000 | 15695 | 1.91 | 0.77 |
|
|
458
|
-
| amazon_counterfactual | 5000 | 4992 | 0.16 | 0.33 |
|
|
459
|
-
| ag_news | 120000 | 106921 | 10.90 | 5.20 |
|
|
460
|
-
| enron_spam | 31716 | 20540 | 35.24 | 2.03 |
|
|
461
|
-
| subj | 8000 | 7990 | 0.12 | 0.63 |
|
|
462
|
-
| sst5 | 8544 | 8526 | 0.21 | 0.58 |
|
|
463
|
-
| 20_newgroups | 11314 | 10684 | 5.57 | 0.73 |
|
|
464
|
-
| hatespeech_offensive | 22783 | 22090 | 3.04 | 0.92 |
|
|
465
|
-
| ade | 17637 | 15718 | 10.88 | 0.73 |
|
|
466
|
-
| imdb | 25000 | 24830 | 0.68 | 1.76 |
|
|
467
|
-
| massive_scenario | 11514 | 9366 | 18.66 | 0.47 |
|
|
468
|
-
| student | 117519 | 63856 | 45.66 | 8.80 |
|
|
469
|
-
| squad_v2 | 130319 | 109698 | 15.82 | 8.81 |
|
|
470
|
-
| wikitext | 1801350 | 884645 | 50.89 | 83.53 |
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
### Train/Test Deduplication Benchmark
|
|
474
|
-
|
|
475
|
-
| Dataset | Train Size | Test Size | Deduplicated Test Size | % Removed | Deduplication Time (s) |
|
|
476
|
-
|----------------------|--------------|--------------|--------------------------|------------|--------------------------|
|
|
477
|
-
| bbc | 1225 | 1000 | 870 | 13.00 | 0.71 |
|
|
478
|
-
| senteval_cr | 3012 | 753 | 750 | 0.40 | 0.13 |
|
|
479
|
-
| tweet_sentiment_extraction | 27481 | 3534 | 3412 | 3.45 | 1.53 |
|
|
480
|
-
| emotion | 16000 | 2000 | 1926 | 3.70 | 0.65 |
|
|
481
|
-
| amazon_counterfactual | 5000 | 5000 | 4990 | 0.20 | 0.51 |
|
|
482
|
-
| ag_news | 120000 | 7600 | 6198 | 18.45 | 3.74 |
|
|
483
|
-
| enron_spam | 31716 | 2000 | 1060 | 47.00 | 1.94 |
|
|
484
|
-
| subj | 8000 | 2000 | 1999 | 0.05 | 0.62 |
|
|
485
|
-
| sst5 | 8544 | 2210 | 2205 | 0.23 | 0.59 |
|
|
486
|
-
| 20_newgroups | 11314 | 7532 | 7098 | 5.76 | 2.25 |
|
|
487
|
-
| hatespeech_offensive | 22783 | 2000 | 1925 | 3.75 | 0.77 |
|
|
488
|
-
| ade | 17637 | 5879 | 4952 | 15.77 | 0.81 |
|
|
489
|
-
| imdb | 25000 | 25000 | 24795 | 0.82 | 2.81 |
|
|
490
|
-
| massive_scenario | 11514 | 2974 | 2190 | 26.36 | 0.46 |
|
|
491
|
-
| student | 117519 | 5000 | 2393 | 52.14 | 3.78 |
|
|
492
|
-
| squad_v2 | 130319 | 11873 | 11863 | 0.08 | 7.13 |
|
|
493
|
-
| wikitext | 1801350 | 4358 | 2139 | 50.92 | 40.32 |
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
As can be seen, SemHash is extremely fast, and scales to large datasets with millions of records. There are some notable examples of train/test leakage, such as `enron_spam` and `student`, where the test dataset contains a significant amount of semantic overlap with the training dataset.
|
|
497
|
-
|
|
498
|
-
### Reproducing the Benchmarks
|
|
499
|
-
|
|
500
|
-
To run the benchmarks yourself, you can use the following command (assuming you have the `datasets` library installed):
|
|
586
|
+
SemHash is extremely fast and scales to large datasets with millions of records. We've benchmarked both text and image deduplication across a variety of datasets. For example, deduplicating text 1.8M records takes only ~83 seconds on CPU.
|
|
587
|
+
|
|
588
|
+
For detailed benchmark results and analysis, see the [benchmarks directory](benchmarks/README.md).
|
|
589
|
+
|
|
590
|
+
### Running Benchmarks
|
|
501
591
|
|
|
502
592
|
```bash
|
|
503
|
-
|
|
593
|
+
# Run text benchmarks
|
|
594
|
+
make benchmark-text
|
|
595
|
+
|
|
596
|
+
# Run image benchmarks
|
|
597
|
+
make benchmark-image
|
|
598
|
+
|
|
599
|
+
# Run all benchmarks
|
|
600
|
+
make benchmark
|
|
504
601
|
```
|
|
505
|
-
Optionally, the datasets can be updated in the [data.py](https://github.com/MinishLab/semhash/blob/main/benchmarks/data.py) file.
|
|
506
602
|
|
|
507
603
|
## License
|
|
508
604
|
|
|
@@ -513,9 +609,12 @@ MIT
|
|
|
513
609
|
If you use SemHash in your research, please cite the following:
|
|
514
610
|
```bibtex
|
|
515
611
|
@software{minishlab2025semhash,
|
|
516
|
-
author
|
|
517
|
-
title
|
|
518
|
-
year
|
|
519
|
-
|
|
612
|
+
author = {{van Dongen}, Thomas and Stephan Tulkens},
|
|
613
|
+
title = {SemHash: Fast Multimodal Semantic Deduplication \& Filtering},
|
|
614
|
+
year = {2025},
|
|
615
|
+
publisher = {Zenodo},
|
|
616
|
+
doi = {10.5281/zenodo.17265942},
|
|
617
|
+
url = {https://github.com/MinishLab/semhash},
|
|
618
|
+
license = {MIT}
|
|
520
619
|
}
|
|
521
620
|
```
|