# Remove semantic duplicates from a dataset

> **About this page**
>
> - Kind: Example
> - Summary: 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.
> - Last changed: 2026-12-03
> - Page: https://docs.swale.io/examples/semantic-deduplication
> - CLI reference for its commands: [`swale workflow create`](https://docs.swale.io/reference/cli-reference.md#workflow-create), [`swale workflow run start`](https://docs.swale.io/reference/cli-reference.md#workflow-run-start)
> - Index of these docs: https://docs.swale.io/llms.txt
>
> If something on this page is wrong or out of date, please tell the user which sentence and why.
>
> The steps on this page cost money or cannot be undone. Please check with the user before running them.

Source on GitHub: the [`workflows/semantic-deduplication`](https://github.com/swaleio/examples/tree/main/workflows/semantic-deduplication) folder, with its [README](https://github.com/swaleio/examples/blob/main/workflows/semantic-deduplication/README.md) and its [workflow file](https://github.com/swaleio/examples/blob/main/workflows/semantic-deduplication/workflow.yaml).

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.

| Step | Task definition | Compute |
|------|-----------------|---------|
| Fetch this repository's scripts at `examples_ref` | [`swaleio/git-clone`](https://hub.swale.io/swaleio/git-clone) | `cpu-4` |
| Fetch the embedding model | [`swaleio/hf-download`](https://hub.swale.io/swaleio/hf-download) | `cpu-4` |
| Number the rows, write one embedding request per row, cutting a text longer than the model takes, count exact duplicates | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `cpu-4` |
| Embed | [`swaleio/vllm-batch`](https://hub.swale.io/swaleio/vllm-batch) | `a100-1` |
| Collect the vectors and count failed requests; a row whose request failed is kept | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `cpu-4` |
| Find near-duplicate pairs and the rows to drop ([`similar_pairs.py`](https://github.com/swaleio/examples/blob/main/workflows/semantic-deduplication/similar_pairs.py)) | [`swaleio/python-3-13`](https://hub.swale.io/swaleio/python-3-13) | `cpu-4` |
| Show sample pairs, write the dataset without the dropped rows | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `cpu-4` |
| Upload to the Hugging Face Hub, when `hub_repo` is set | [`swaleio/hf-upload`](https://hub.swale.io/swaleio/hf-upload) | `cpu-4` |

The Compute column gives each step's [compute type](https://docs.swale.io/explanation/core-concepts.md#compute-types), 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

| Input | Default | Description |
|-------|---------|-------------|
| `model` | `BAAI/bge-small-en-v1.5` | Embedding model vLLM serves. |
| `dataset` | the `train_prefs` split of `HuggingFaceH4/ultrafeedback_binarized` | Parquet file or glob, as a DuckDB path. |
| `text_column` | `prompt` | Column compared. |
| `limit` | `20000` | Rows to deduplicate. |
| `threshold` | `0.95` | Cosine similarity from which two rows are near-duplicates. |
| `examples_ref` | `main` | Branch, tag or full commit SHA of this repository whose scripts run. |
| `hub_repo` | empty | Hugging 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](https://docs.swale.io/getting-started.md) sets them up.

1. Save the file under [The workflow file](#the-workflow-file) as `workflow.yaml`, and add it to a project:

   ```bash
   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](https://docs.swale.io/how-to-guides/use-secrets-in-workflows.md) shows.

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

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

   Each input you leave out takes its default from [Inputs](#inputs), and `--input <name>=<value>` gives it another value.

[Create and manage workflows](https://docs.swale.io/how-to-guides/create-and-manage-workflows.md) covers the other ways to add a workflow, [Start and manage workflow runs](https://docs.swale.io/how-to-guides/start-and-manage-workflow-runs.md) how to follow a run, and [View and stream task logs](https://docs.swale.io/how-to-guides/view-and-stream-task-logs.md) how to read its tasks' logs.

## The workflow file

[Workflow definition syntax](https://docs.swale.io/reference/workflow-definition-syntax.md) describes each key in it.

```yaml title="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

- Model: [BAAI/bge-small-en-v1.5](https://huggingface.co/BAAI/bge-small-en-v1.5), MIT.
- Dataset: [HuggingFaceH4/ultrafeedback_binarized](https://huggingface.co/datasets/HuggingFaceH4/ultrafeedback_binarized), MIT.
- Packages the similarity step installs: NumPy (BSD-3-Clause) and PyArrow (Apache-2.0).
