Skip to main content

Remove semantic duplicates from a dataset

Source on GitHub: the workflows/semantic-deduplication folder, with its README and its workflow file.

Removes rows that say nearly the same thing in different words, which exact deduplication misses. vLLM embeds every row, a short NumPy script compares every row with every other and groups the pairs above a similarity threshold, and DuckDB keeps one row of each group and shows the closest pairs it judged different, so the threshold can be checked.

StepTask definitionCompute
Fetch this repository's scripts at examples_refswaleio/git-clonecpu-4
Fetch the embedding modelswaleio/hf-downloadcpu-4
Number the rows, write one embedding request per row, cutting a text longer than the model takes, count exact duplicatesswaleio/duckdbcpu-4
Embedswaleio/vllm-batcha100-1
Collect the vectors and count failed requests; a row whose request failed is keptswaleio/duckdbcpu-4
Find near-duplicate pairs and the rows to drop (similar_pairs.py)swaleio/python-3-13cpu-4
Show sample pairs, write the dataset without the dropped rowsswaleio/duckdbcpu-4
Upload to the Hugging Face Hub, when hub_repo is setswaleio/hf-uploadcpu-4

The Compute column gives each step's compute type, the compute its tasks are allocated.

What stays one script: the similarity step. Comparing every row with every other is one matrix product per block of rows, and grouping the pairs needs all of them at once.

Inputs​

InputDefaultDescription
modelBAAI/bge-small-en-v1.5Embedding model vLLM serves.
datasetthe train_prefs split of HuggingFaceH4/ultrafeedback_binarizedParquet file or glob, as a DuckDB path.
text_columnpromptColumn compared.
limit20000Rows to deduplicate.
threshold0.95Cosine similarity from which two rows are near-duplicates.
examples_refmainBranch, tag or full commit SHA of this repository whose scripts run.
hub_repoemptyHugging Face dataset repo to upload the result to, as data/train.parquet.

The download and the upload read the secret hf_token.

Output​

deduplicated.parquet on the workspace, the similar pairs in pairs.parquet and the dropped row ids in drop.parquet.

Run it​

You need the CLI, logged in to your account, and a project to add the workflow to; Getting started sets them up.

  1. Save the file under The workflow file as workflow.yaml, and add it to a project:

    swale workflow create --project-name my-project --file workflow.yaml

    The command prints Workflow created: followed by the workflow's ID.

  2. The workflow reads the secret hf_token. Create it as a project secret, or as an account secret that allows the project, as Use secrets in workflows shows.

  3. Start a run with the workflow's ID:

    swale workflow run start --project-name my-project --workflow-id <workflow-id>

    Each input you leave out takes its default from Inputs, and --input <name>=<value> gives it another value.

Create and manage workflows covers the other ways to add a workflow, Start and manage workflow runs how to follow a run, and View and stream task logs how to read its tasks' logs.

The workflow file​

Workflow definition syntax describes each key in it.

workflow.yaml
name: Remove semantic duplicates from a dataset
description: Embeds every row of a dataset with vLLM batch inference, finds pairs of rows that mean nearly the same, and writes the dataset without the near-duplicates.
compute_type: cpu-4

inputs:
model:
description: Hugging Face repo id of an embedding model vLLM serves.
default: BAAI/bge-small-en-v1.5
dataset:
description: Parquet file or glob, as a DuckDB path.
default: hf://datasets/HuggingFaceH4/ultrafeedback_binarized/data/train_prefs-*.parquet
text_column:
description: Column whose meaning is compared.
default: prompt
limit:
description: Rows to deduplicate.
default: "20000"
threshold:
description: Cosine similarity from which two rows count as near-duplicates.
default: "0.95"
examples_ref:
description: Branch, tag or full commit SHA of swaleio/examples whose scripts run.
default: main
hub_repo:
description: Hugging Face dataset repo to upload the deduplicated dataset to, as namespace/name. Leave empty to keep it on the workspace only.
default: ""

entry_point: main

blocks:
main:
tasks:
fetch_scripts:
name: Fetch the example scripts
uses: swaleio/git-clone
args:
repository_url: https://github.com/swaleio/examples.git
revision: ${{inputs.examples_ref}}
dest: ${{env.WORKFLOW_STORAGE}}/examples

fetch_model:
name: Fetch the model
uses: swaleio/hf-download
args:
repo: ${{inputs.model}}
dest: ${{env.WORKFLOW_STORAGE}}/model
token: ${{secrets.hf_token}}

requests:
name: Write embedding requests
uses: swaleio/duckdb
args:
sql: |
CREATE TABLE rows AS
SELECT row_number() OVER () - 1 AS id, *
FROM (SELECT * FROM '${{inputs.dataset}}' LIMIT ${{inputs.limit}});
COPY rows TO '${{env.WORKFLOW_STORAGE}}/rows.parquet' (FORMAT parquet);
COPY (SELECT id::VARCHAR AS custom_id, 'POST' AS method, '/v1/embeddings' AS url,
{'model': '${{env.WORKFLOW_STORAGE}}/model', 'input': "${{inputs.text_column}}",
'truncate_prompt_tokens': -1} AS body
FROM rows)
TO '${{env.WORKFLOW_STORAGE}}/requests.jsonl' (FORMAT json);
SELECT count(*) AS rows, count(DISTINCT "${{inputs.text_column}}") AS exactly_distinct FROM rows;

embed:
name: Embed
uses: swaleio/vllm-batch
compute_type: a100-1
start_on:
- fetch_model
- requests
args:
model: ${{env.WORKFLOW_STORAGE}}/model
input_file: ${{env.WORKFLOW_STORAGE}}/requests.jsonl
output_file: ${{env.WORKFLOW_STORAGE}}/embeddings.jsonl

collect:
name: Collect vectors
uses: swaleio/duckdb
start_on:
- embed
args:
sql: |
CREATE TABLE responses AS SELECT * FROM read_json('${{env.WORKFLOW_STORAGE}}/embeddings.jsonl');
COPY (SELECT custom_id::BIGINT AS id, response.body.data[1].embedding::FLOAT[] AS embedding
FROM responses WHERE response.status_code = 200)
TO '${{env.WORKFLOW_STORAGE}}/vectors.parquet' (FORMAT parquet);
SELECT count(*) FILTER (WHERE response.status_code = 200) AS vectors,
count(*) FILTER (WHERE response.status_code IS DISTINCT FROM 200) AS failed,
len(any_value(response.body.data[1].embedding)) AS dimensions
FROM responses;

find_pairs:
name: Find near-duplicate pairs
uses: swaleio/python-3-13
start_on:
- fetch_scripts
- collect
args:
script: |
import os, subprocess, sys

storage = os.environ["WORKFLOW_STORAGE"]
examples = f"{storage}/examples"
subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "--target", "/tmp/deps",
"-r", f"{examples}/requirements/cpu-numpy.txt"], check=True)
subprocess.run([sys.executable, f"{examples}/workflows/semantic-deduplication/similar_pairs.py",
"--embeddings", f"{storage}/vectors.parquet", "--threshold", "${{inputs.threshold}}",
"--pairs", f"{storage}/pairs.parquet", "--drop", f"{storage}/drop.parquet"],
env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True)

drop_rows:
name: Drop the near-duplicates
uses: swaleio/duckdb
start_on:
- find_pairs
args:
sql: |
SELECT p.similarity, left(a."${{inputs.text_column}}", 70) AS kept, left(b."${{inputs.text_column}}", 70) AS dropped
FROM '${{env.WORKFLOW_STORAGE}}/pairs.parquet' p
JOIN '${{env.WORKFLOW_STORAGE}}/rows.parquet' a ON a.id = p.left_id
JOIN '${{env.WORKFLOW_STORAGE}}/rows.parquet' b ON b.id = p.right_id
WHERE a."${{inputs.text_column}}" <> b."${{inputs.text_column}}"
ORDER BY p.similarity LIMIT 10;
COPY (SELECT * EXCLUDE (id) FROM '${{env.WORKFLOW_STORAGE}}/rows.parquet'
WHERE id NOT IN (SELECT id FROM '${{env.WORKFLOW_STORAGE}}/drop.parquet') ORDER BY id)
TO '${{env.WORKFLOW_STORAGE}}/deduplicated.parquet' (FORMAT parquet);
SELECT (SELECT count(*) FROM '${{env.WORKFLOW_STORAGE}}/rows.parquet') AS rows_before,
(SELECT count(*) FROM '${{env.WORKFLOW_STORAGE}}/deduplicated.parquet') AS rows_after;

publish:
name: Upload when asked
start_on:
- drop_rows
if:
condition: ${{inputs.hub_repo}}
true: upload

upload:
tasks:
upload_dataset:
name: Upload to the Hugging Face Hub
uses: swaleio/hf-upload
args:
repo: ${{inputs.hub_repo}}
repo_type: dataset
source: ${{env.WORKFLOW_STORAGE}}/deduplicated.parquet
path_in_repo: data/train.parquet
token: ${{secrets.hf_token}}

Licenses​