Train a few-shot classifier with SetFit
Source on GitHub: the workflows/setfit-classifier folder, with its README and its workflow file.
Trains a text classifier from a few labeled examples per class with SetFit: it fine-tunes a sentence-embedding model on pairs of the examples, then fits a classification head on the embeddings. Useful when labeling hundreds of examples is not an option. The prediction and the scores are separate steps.
| 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 |
Draw per_label examples of each label, the same ones every run | swaleio/duckdb | cpu-4 |
Train (train.py) | swaleio/transformers | a100-1 |
Predict the eval split (predict.py) | swaleio/transformers | a100-1 |
| Compute accuracy, per-class F1 and macro F1 | swaleio/duckdb | cpu-4 |
Upload the classifier, 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.
What stays one script: training. SetFit's two stages, contrastive
fine-tuning of the embedding model and fitting the head, both run inside one
Trainer.train() call.
Inputs
| Input | Default | Description |
|---|---|---|
model | sentence-transformers/all-MiniLM-L6-v2 | Sentence-embedding model SetFit starts from. |
train_data, eval_data | the train and validation splits of google-research-datasets/poem_sentiment | Parquet files or globs, as DuckDB paths. |
text_column, label_column | verse_text, label | Columns holding the text and the label number. |
labels | negative,positive,no_impact,mixed | Label names in label-number order. |
per_label | 16 | Training examples per label. |
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 classifier to. |
The download and the upload read the secret hf_token.
Output
The classifier in model/ on the workspace, the predictions in
predictions.parquet, and metrics.json with accuracy and macro F1.
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: Train a few-shot classifier with SetFit
description: Trains a text classifier from a handful of examples per label with SetFit, then predicts the eval split on a GPU and computes accuracy and macro F1 in SQL.
compute_type: cpu-4
inputs:
model:
description: Hugging Face repo id of the sentence-embedding model SetFit starts from.
default: sentence-transformers/all-MiniLM-L6-v2
train_data:
description: Parquet file or glob to draw the few training examples from, as a DuckDB path.
default: hf://datasets/google-research-datasets/poem_sentiment/data/train-00000-of-00001.parquet
eval_data:
description: Parquet file or glob of evaluation rows, as a DuckDB path.
default: hf://datasets/google-research-datasets/poem_sentiment/data/validation-00000-of-00001.parquet
text_column:
description: Column holding the text.
default: verse_text
label_column:
description: Column holding the label, as a number from 0.
default: label
labels:
description: Label names, separated by commas, in label-number order.
default: negative,positive,no_impact,mixed
per_label:
description: Training examples drawn for each label.
default: "16"
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 classifier 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: Draw the few examples
uses: swaleio/duckdb
args:
sql: |
-- The same rows every time: each label's first rows in a fixed hash order.
COPY (
SELECT text, label FROM (
SELECT "${{inputs.text_column}}" AS text, "${{inputs.label_column}}"::BIGINT AS label,
row_number() OVER (PARTITION BY "${{inputs.label_column}}" ORDER BY hash("${{inputs.text_column}}")) AS n
FROM '${{inputs.train_data}}')
WHERE n <= ${{inputs.per_label}}
) TO '${{env.WORKFLOW_STORAGE}}/few-shot.parquet' (FORMAT parquet);
COPY (SELECT "${{inputs.text_column}}" AS text, "${{inputs.label_column}}"::BIGINT AS label FROM '${{inputs.eval_data}}')
TO '${{env.WORKFLOW_STORAGE}}/eval.parquet' (FORMAT parquet);
SELECT label, count(*) AS examples FROM '${{env.WORKFLOW_STORAGE}}/few-shot.parquet' GROUP BY label ORDER BY label;
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"
for requirements in ("gpu-sentence-transformers.txt", "gpu-setfit.txt"):
subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "--no-deps", "--target", "/tmp/deps",
"-r", f"{examples}/requirements/{requirements}"], check=True)
subprocess.run([sys.executable, f"{examples}/workflows/setfit-classifier/train.py",
"--model", f"{storage}/base-model", "--train", f"{storage}/few-shot.parquet",
"--labels", "${{inputs.labels}}", "--output", f"{storage}/model"],
env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True)
predict:
name: Predict the eval split
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"
for requirements in ("gpu-sentence-transformers.txt", "gpu-setfit.txt"):
subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "--no-deps", "--target", "/tmp/deps",
"-r", f"{examples}/requirements/{requirements}"], check=True)
subprocess.run([sys.executable, f"{examples}/workflows/setfit-classifier/predict.py",
"--model", f"{storage}/model", "--eval", f"{storage}/eval.parquet",
"--output", f"{storage}/predictions.parquet"],
env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True)
score:
name: Score
uses: swaleio/duckdb
start_on:
- predict
args:
sql: |
CREATE TABLE predictions AS SELECT * FROM '${{env.WORKFLOW_STORAGE}}/predictions.parquet';
CREATE TABLE per_class AS
WITH classes AS (SELECT DISTINCT label AS class FROM predictions)
SELECT string_split($$${{inputs.labels}}$$, ',')[class + 1] AS label,
sum((p.label = class AND p.prediction = class)::INT) AS tp,
sum((p.label <> class AND p.prediction = class)::INT) AS fp,
sum((p.label = class AND p.prediction <> class)::INT) AS fn
FROM classes, predictions p GROUP BY class ORDER BY class;
SELECT label, tp + fn AS rows,
round(CASE WHEN 2 * tp + fp + fn = 0 THEN 0 ELSE 2.0 * tp / (2 * tp + fp + fn) END, 4) AS f1
FROM per_class;
COPY (SELECT (SELECT count(*) FROM predictions) AS rows,
(SELECT round(avg((label = prediction)::INT), 4) FROM predictions) AS accuracy,
(SELECT round(avg(CASE WHEN 2 * tp + fp + fn = 0 THEN 0 ELSE 2.0 * tp / (2 * tp + fp + fn) END), 4) FROM per_class) AS macro_f1)
TO '${{env.WORKFLOW_STORAGE}}/metrics.json' (FORMAT json);
SELECT * FROM '${{env.WORKFLOW_STORAGE}}/metrics.json';
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: google-research-datasets/poem_sentiment, CC BY 4.0.
- Packages the GPU steps install: SetFit, Sentence Transformers and evaluate (Apache-2.0), scikit-learn, SciPy, joblib, threadpoolctl and cloudpickle (BSD-3-Clause) and narwhals (MIT).