Fine-tune sentence embeddings for retrieval
Source on GitHub: the workflows/sentence-embeddings folder, with its README and its workflow file.
Fine-tunes a sentence-embedding model with Sentence Transformers so that a question lands close to the text that answers it, then checks that retrieval got better: the base model and the fine-tuned model each embed the same held-out questions and answers, and SQL ranks every answer for every question and reports recall at 1 and 10 and the mean reciprocal rank for both.
| Step | Task definition | Compute |
|---|---|---|
Fetch this repository's scripts at examples_ref | swaleio/git-clone | cpu-4 |
| Fetch the model | swaleio/hf-download | cpu-4 |
| Build the train and eval pairs | swaleio/duckdb | cpu-4 |
Train with multiple-negatives ranking loss (train.py) | swaleio/transformers | a100-1 |
Embed the eval pairs with the base model, and with the fine-tuned model (embed.py) | swaleio/transformers | a100-1 each |
| Rank and compare retrieval | swaleio/duckdb | cpu-4 |
Upload the model, when hub_repo is set | swaleio/hf-upload | cpu-4 |
The Compute column gives each step's compute type, the compute its tasks are allocated.
The base model embeds the eval pairs while the other one trains.
What stays one script: the training loop, which holds the model, the optimizer and the batches together on one GPU. With multiple-negatives ranking loss each batch's other pairs are its negatives, so the batch cannot be split either.
Inputs
| Input | Default | Description |
|---|---|---|
model | sentence-transformers/all-MiniLM-L6-v2 | Sentence-embedding model to fine-tune. |
train_data, eval_data | the train and test splits of openai/gsm8k | Parquet files or globs, as DuckDB paths. |
anchor_column | question | Column holding the query side of each pair. |
positive_column | answer | Column holding the text that answers it. |
epochs | 1 | Training epochs. |
examples_ref | main | Branch, tag or full commit SHA of this repository whose scripts run. |
hub_repo | empty | Hugging Face model repo to upload the model to. |
The download and the upload read the secret hf_token.
Output
The fine-tuned model in model/ on the workspace, both models' vectors in
vectors-base.parquet and vectors-tuned.parquet, and the comparison in the
last task's log.
Run it
You need the CLI, logged in to your account, and a project to add the workflow to; Getting started sets them up.
-
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.yamlThe command prints
Workflow created:followed by the workflow's ID. -
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. -
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.
name: Fine-tune sentence embeddings for retrieval
description: Fine-tunes a sentence-embedding model on question and answer pairs, then compares its retrieval recall and MRR with the base model's on held-out pairs in SQL.
compute_type: cpu-4
inputs:
model:
description: Hugging Face repo id of the sentence-embedding model to fine-tune.
default: sentence-transformers/all-MiniLM-L6-v2
train_data:
description: Parquet file or glob of training pairs, as a DuckDB path.
default: hf://datasets/openai/gsm8k/main/train-*.parquet
eval_data:
description: Parquet file or glob of held-out pairs, as a DuckDB path.
default: hf://datasets/openai/gsm8k/main/test-*.parquet
anchor_column:
description: Column holding the query side of each pair.
default: question
positive_column:
description: Column holding the document that answers it.
default: answer
epochs:
description: Training epochs.
default: "1"
examples_ref:
description: Branch, tag or full commit SHA of swaleio/examples whose scripts run.
default: main
hub_repo:
description: Hugging Face model repo to upload the fine-tuned model 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}}/base-model
token: ${{secrets.hf_token}}
prepare:
name: Build the pairs
uses: swaleio/duckdb
args:
sql: |
COPY (SELECT DISTINCT "${{inputs.anchor_column}}" AS anchor, "${{inputs.positive_column}}" AS positive
FROM '${{inputs.train_data}}')
TO '${{env.WORKFLOW_STORAGE}}/train-pairs.parquet' (FORMAT parquet);
COPY (SELECT row_number() OVER () AS id, "${{inputs.anchor_column}}" AS anchor, "${{inputs.positive_column}}" AS positive
FROM '${{inputs.eval_data}}')
TO '${{env.WORKFLOW_STORAGE}}/eval-pairs.parquet' (FORMAT parquet);
SELECT (SELECT count(*) FROM '${{env.WORKFLOW_STORAGE}}/train-pairs.parquet') AS train_pairs,
(SELECT count(*) FROM '${{env.WORKFLOW_STORAGE}}/eval-pairs.parquet') AS eval_pairs;
train:
name: Train
uses: swaleio/transformers
compute_type: a100-1
start_on:
- fetch_scripts
- fetch_model
- prepare
args:
script: |
import os, subprocess, sys
storage = os.environ["WORKFLOW_STORAGE"]
examples = f"{storage}/examples"
subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "--no-deps", "--target", "/tmp/deps",
"-r", f"{examples}/requirements/gpu-sentence-transformers.txt"], check=True)
subprocess.run([sys.executable, f"{examples}/workflows/sentence-embeddings/train.py",
"--model", f"{storage}/base-model", "--pairs", f"{storage}/train-pairs.parquet",
"--epochs", "${{inputs.epochs}}", "--output", f"{storage}/model"],
env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True)
embed_base:
name: Embed with the base model
uses: swaleio/transformers
compute_type: a100-1
start_on:
- fetch_scripts
- fetch_model
- prepare
args:
script: |
import os, subprocess, sys
storage = os.environ["WORKFLOW_STORAGE"]
examples = f"{storage}/examples"
subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "--no-deps", "--target", "/tmp/deps",
"-r", f"{examples}/requirements/gpu-sentence-transformers.txt"], check=True)
subprocess.run([sys.executable, f"{examples}/workflows/sentence-embeddings/embed.py",
"--model", f"{storage}/base-model", "--pairs", f"{storage}/eval-pairs.parquet",
"--output", f"{storage}/vectors-base.parquet"],
env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True)
embed_tuned:
name: Embed with the fine-tuned model
uses: swaleio/transformers
compute_type: a100-1
start_on:
- train
args:
script: |
import os, subprocess, sys
storage = os.environ["WORKFLOW_STORAGE"]
examples = f"{storage}/examples"
subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "--no-deps", "--target", "/tmp/deps",
"-r", f"{examples}/requirements/gpu-sentence-transformers.txt"], check=True)
subprocess.run([sys.executable, f"{examples}/workflows/sentence-embeddings/embed.py",
"--model", f"{storage}/model", "--pairs", f"{storage}/eval-pairs.parquet",
"--output", f"{storage}/vectors-tuned.parquet"],
env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True)
score:
name: Compare retrieval
uses: swaleio/duckdb
start_on:
- embed_base
- embed_tuned
args:
sql: |
-- Each query's own answer is the one document that counts as relevant. The
-- vectors are normalized, so their dot product is their cosine similarity.
CREATE TABLE vectors AS
SELECT 'base' AS model, * FROM '${{env.WORKFLOW_STORAGE}}/vectors-base.parquet'
UNION ALL
SELECT 'fine-tuned', * FROM '${{env.WORKFLOW_STORAGE}}/vectors-tuned.parquet';
CREATE TABLE ranks AS
SELECT model, query, rank FROM (
SELECT q.model, q.id AS query, d.id AS document,
row_number() OVER (PARTITION BY q.model, q.id
ORDER BY list_dot_product(q.embedding, d.embedding) DESC) AS rank
FROM vectors q JOIN vectors d ON q.model = d.model AND q.role = 'query' AND d.role = 'document')
WHERE query = document;
SELECT model, count(*) AS queries,
round(avg((rank = 1)::INT), 4) AS recall_at_1,
round(avg((rank <= 10)::INT), 4) AS recall_at_10,
round(avg(1.0 / rank), 4) AS mrr
FROM ranks GROUP BY model ORDER BY model;
publish:
name: Upload when asked
start_on:
- score
if:
condition: ${{inputs.hub_repo}}
true: upload
upload:
tasks:
upload_model:
name: Upload to the Hugging Face Hub
uses: swaleio/hf-upload
args:
repo: ${{inputs.hub_repo}}
source: ${{env.WORKFLOW_STORAGE}}/model
token: ${{secrets.hf_token}}
Licenses
- Model: sentence-transformers/all-MiniLM-L6-v2, Apache-2.0.
- Dataset: openai/gsm8k, MIT.
- Packages the GPU steps install: Sentence Transformers (Apache-2.0), scikit-learn, SciPy, joblib, threadpoolctl and cloudpickle (BSD-3-Clause) and narwhals (MIT).