Skip to main content

Embed a dataset

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

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.

StepTask definitionCompute
Number the rows and split them into shardsswaleio/duckdbcpu-4
Serve the embedding model, as a runnerswaleio/tei-servea100-1
Wait for the server, checking every 5 secondsswaleio/http-requestcpu-4
For each shard: embed its rows, 32 per requestswaleio/python-3-13cpu-4
Gather the vectors into embeddings.parquetswaleio/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.

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​

InputDefaultDescription
modelBAAI/bge-small-en-v1.5Embedding model on the Hugging Face Hub.
datasetthe train split of openai/gsm8kParquet file or glob, as a DuckDB path.
text_columnquestionColumn to embed.
shards["0", "1", "2", "3"]One client task per element.
hub_repoemptyHugging 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 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: 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​