# Embed a dataset

> **About this page**
>
> - Kind: Example
> - Summary: Serves an embedding model with Text Embeddings Inference and embeds every row of a dataset into one Parquet file, with one client task per shard in parallel.
> - Last changed: 2026-12-03
> - Page: https://docs.swale.io/examples/embed-dataset
> - 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/embed-dataset`](https://github.com/swaleio/examples/tree/main/workflows/embed-dataset) folder, with its [README](https://github.com/swaleio/examples/blob/main/workflows/embed-dataset/README.md) and its [workflow file](https://github.com/swaleio/examples/blob/main/workflows/embed-dataset/workflow.yaml).

Computes a vector for every row of a dataset with an embedding model, for
search, clustering or deduplication. Text Embeddings Inference serves the
model on a GPU, and several small client tasks, one per shard, send it the
rows at the same time; a last step gathers the vectors into one Parquet file.
When the clients are done, the platform stops the server.

| Step | Task definition | Compute |
|------|-----------------|---------|
| Number the rows and split them into shards | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `cpu-4` |
| Serve the embedding model, as a runner | [`swaleio/tei-serve`](https://hub.swale.io/swaleio/tei-serve) | `a100-1` |
| Wait for the server, checking every 5 seconds | [`swaleio/http-request`](https://hub.swale.io/swaleio/http-request) | `cpu-4` |
| For each shard: embed its rows, 32 per request | [`swaleio/python-3-13`](https://hub.swale.io/swaleio/python-3-13) | `cpu-4` |
| Gather the vectors into `embeddings.parquet` | [`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.

Every step is its own task. Each client is a short Python script that uses only
the standard library.

`swaleio/vllm-batch` can also embed, through `/v1/embeddings` requests, when
vLLM supports the model; Text Embeddings Inference serves more embedding and
reranker architectures and is built for this one job.

## Inputs

| Input | Default | Description |
|-------|---------|-------------|
| `model` | `BAAI/bge-small-en-v1.5` | Embedding model on the Hugging Face Hub. |
| `dataset` | the train split of `openai/gsm8k` | Parquet file or glob, as a DuckDB path. |
| `text_column` | `question` | Column to embed. |
| `shards` | `["0", "1", "2", "3"]` | One client task per element. |
| `hub_repo` | empty | Hugging Face dataset repo to upload the embeddings to, as `data/train.parquet`. |

The upload reads the secret `hf_token`.

## Output

`embeddings.parquet` on the workspace, with `id`, `text` and `embedding` (a
`FLOAT[]`) for every row.

## 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: Embed a dataset
description: Serves an embedding model with Text Embeddings Inference and embeds every row of a dataset into one Parquet file, with one client task per shard in parallel.
compute_type: cpu-4

inputs:
  model:
    description: Hugging Face repo id of an embedding model Text Embeddings Inference serves.
    default: BAAI/bge-small-en-v1.5
  dataset:
    description: Parquet file or glob, as a DuckDB path.
    default: hf://datasets/openai/gsm8k/main/train-*.parquet
  text_column:
    description: Column holding the text to embed.
    default: question
  shards:
    description: The client shards, as a JSON array; one client task runs per element, and each embeds every nth row.
    default: '["0", "1", "2", "3"]'
  hub_repo:
    description: Hugging Face dataset repo to upload the embeddings to, as namespace/name. Leave empty to keep them on the workspace only.
    default: ""

entry_point: main

blocks:
  main:
    tasks:
      split:
        name: Split into shards
        uses: swaleio/duckdb
        args:
          sql: |
            CREATE TABLE rows AS
              SELECT row_number() OVER () - 1 AS id, "${{inputs.text_column}}" AS text
              FROM '${{inputs.dataset}}';
            CREATE TABLE sharded AS
              SELECT *, id % json_array_length($$${{inputs.shards}}$$) AS shard FROM rows;
            COPY sharded TO '${{env.WORKFLOW_STORAGE}}/shards' (FORMAT json, PARTITION_BY (shard), OVERWRITE_OR_IGNORE);
            COPY rows TO '${{env.WORKFLOW_STORAGE}}/texts.parquet' (FORMAT parquet);
            SELECT shard, count(*) AS rows FROM sharded GROUP BY shard ORDER BY shard;

      serve:
        name: Serve the embedding model
        uses: swaleio/tei-serve
        compute_type: a100-1
        terminate_on:
          - each_shard
        args:
          model: ${{inputs.model}}

      wait_ready:
        name: Wait for the server
        uses: swaleio/http-request
        start_on:
          - serve
        args:
          url: http://${{tasks.serve.ip-address}}:8080/health
          retry: "360"
          retry_delay: "5"
          expected_status: "200"

      each_shard:
        name: Embed each shard
        start_on:
          - wait_ready
          - split
        for_each:
          items: ${{inputs.shards}}
          block: embed_shard

      collect:
        name: Collect embeddings
        uses: swaleio/duckdb
        start_on:
          - each_shard
        args:
          sql: |
            CREATE TABLE embedded AS
              SELECT t.id, t.text, e.embedding::FLOAT[] AS embedding
              FROM '${{env.WORKFLOW_STORAGE}}/texts.parquet' t
              JOIN read_json('${{env.WORKFLOW_STORAGE}}/embeddings/*.jsonl', columns = {'id': 'BIGINT', 'embedding': 'DOUBLE[]'}) e
                USING (id)
              ORDER BY t.id;
            SELECT count(*) AS rows, len(any_value(embedding)) AS dimensions FROM embedded;
            COPY embedded TO '${{env.WORKFLOW_STORAGE}}/embeddings.parquet' (FORMAT parquet);

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

  embed_shard:
    tasks:
      embed:
        name: Embed shard
        uses: swaleio/python-3-13
        args:
          script: |
            import glob, json, os, urllib.request

            storage = os.environ["WORKFLOW_STORAGE"]
            shard = "${{tasks.each_shard.for_each.item}}"
            server = "http://${{tasks.serve.ip-address}}:8080/embed"
            os.makedirs(f"{storage}/embeddings", exist_ok=True)
            rows = []
            for path in glob.glob(f"{storage}/shards/shard={shard}/*.json"):
                with open(path) as f:
                    rows += [json.loads(line) for line in f if line.strip()]

            def embed(texts):
                body = json.dumps({"inputs": texts, "truncate": True}).encode()
                request = urllib.request.Request(server, body, {"Content-Type": "application/json"})
                with urllib.request.urlopen(request, timeout=300) as response:
                    return json.load(response)

            with open(f"{storage}/embeddings/{shard}.jsonl", "w") as out:
                for start in range(0, len(rows), 32):
                    batch = rows[start:start + 32]
                    for row, vector in zip(batch, embed([r["text"] for r in batch])):
                        out.write(json.dumps({"id": row["id"], "embedding": vector}) + "\n")
            print(f"shard {shard}: embedded {len(rows)} rows")

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

## Licenses of the defaults

- Model: [BAAI/bge-small-en-v1.5](https://huggingface.co/BAAI/bge-small-en-v1.5), MIT.
- Dataset: [openai/gsm8k](https://huggingface.co/datasets/openai/gsm8k), MIT.
