Fine-tune an encoder for text regression
Source on GitHub: the workflows/text-regression folder, with its README and its workflow file.
Fine-tunes an encoder model to predict a number for each text. The default data is FineWeb-Edu's set of web pages scored from 0 to 5 for educational value, the kind of scorer used to filter pre-training data. Only training and prediction hold a GPU.
| 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 |
| Prepare the train and eval splits, print each one's mean and spread | swaleio/duckdb | cpu-4 |
Tokenize both splits (preprocess.py) | swaleio/python-3-13 | cpu-4 |
Train with one output and a mean-squared-error loss (train.py --regression) | swaleio/transformers | a100-1 |
Predict the eval split (predict.py) | swaleio/transformers | a100-1 |
| Compute mean squared error, mean absolute error, Pearson correlation and rounded accuracy | 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 scripts are the text classification workflow's,
run with --regression.
What stays one script: the training loop, which holds the model, the optimizer and the batches together on one GPU.
Inputs
| Input | Default | Description |
|---|---|---|
model | answerdotai/ModernBERT-base | Encoder model to fine-tune. |
train_data, eval_data | two shards of HuggingFaceFW/fineweb-edu-llama3-annotations | Parquet files or globs, as DuckDB paths. |
text_column | text | Column holding the text. |
target_column | score | Column holding the number to predict. |
train_rows, eval_rows | 20000, 2000 | Rows to use from each. |
epochs | 2 | 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, the predictions in
predictions.parquet, and the error measures in metrics.json.
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 an encoder for text regression
description: Fine-tunes an encoder model to predict a number for each text, here an educational-value score, with training on a GPU and error measures in SQL.
compute_type: cpu-4
inputs:
model:
description: Hugging Face repo id of the encoder model to fine-tune.
default: answerdotai/ModernBERT-base
train_data:
description: Parquet file or glob of training rows, as a DuckDB path.
default: hf://datasets/HuggingFaceFW/fineweb-edu-llama3-annotations/data/train-00000-of-00008.parquet
eval_data:
description: Parquet file or glob of evaluation rows, as a DuckDB path.
default: hf://datasets/HuggingFaceFW/fineweb-edu-llama3-annotations/data/train-00001-of-00008.parquet
text_column:
description: Column holding the text.
default: text
target_column:
description: Column holding the number to predict.
default: score
train_rows:
description: Training rows to use.
default: "20000"
eval_rows:
description: Evaluation rows to use.
default: "2000"
epochs:
description: Training epochs.
default: "2"
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: Prepare the splits
uses: swaleio/duckdb
args:
sql: |
COPY (SELECT "${{inputs.text_column}}" AS text, "${{inputs.target_column}}"::DOUBLE AS label
FROM '${{inputs.train_data}}' LIMIT ${{inputs.train_rows}})
TO '${{env.WORKFLOW_STORAGE}}/train.parquet' (FORMAT parquet);
COPY (SELECT "${{inputs.text_column}}" AS text, "${{inputs.target_column}}"::DOUBLE AS label
FROM '${{inputs.eval_data}}' LIMIT ${{inputs.eval_rows}})
TO '${{env.WORKFLOW_STORAGE}}/eval.parquet' (FORMAT parquet);
SELECT 'train' AS split, count(*) AS rows, round(avg(label), 3) AS mean, round(stddev(label), 3) AS std
FROM '${{env.WORKFLOW_STORAGE}}/train.parquet'
UNION ALL
SELECT 'eval', count(*), round(avg(label), 3), round(stddev(label), 3)
FROM '${{env.WORKFLOW_STORAGE}}/eval.parquet';
tokenize:
name: Tokenize
uses: swaleio/python-3-13
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", "--target", "/tmp/deps",
"-r", f"{examples}/requirements/cpu-tokenize.txt"], check=True)
subprocess.run([sys.executable, f"{examples}/workflows/text-classification/preprocess.py",
"--model", f"{storage}/base-model", "--max-length", "512",
"--train", f"{storage}/train.parquet", "--eval", f"{storage}/eval.parquet",
"--output", f"{storage}/tokenized"],
env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True)
train:
name: Train
uses: swaleio/transformers
compute_type: a100-1
start_on:
- tokenize
args:
script: |
import os, subprocess, sys
storage = os.environ["WORKFLOW_STORAGE"]
subprocess.run([sys.executable, f"{storage}/examples/workflows/text-classification/train.py",
"--model", f"{storage}/base-model", "--data", f"{storage}/tokenized", "--regression",
"--epochs", "${{inputs.epochs}}", "--batch-size", "16",
"--output", f"{storage}/model"], 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"]
subprocess.run([sys.executable, f"{storage}/examples/workflows/text-classification/predict.py",
"--model", f"{storage}/model", "--data", f"{storage}/tokenized/eval",
"--output", f"{storage}/predictions.parquet"], check=True)
score:
name: Score
uses: swaleio/duckdb
start_on:
- predict
args:
sql: |
COPY (
SELECT count(*) AS rows,
round(avg((prediction - label) ^ 2), 4) AS mean_squared_error,
round(avg(abs(prediction - label)), 4) AS mean_absolute_error,
round(corr(prediction, label), 4) AS pearson,
round(avg((round(prediction) = label)::INT), 4) AS rounded_accuracy
FROM '${{env.WORKFLOW_STORAGE}}/predictions.parquet'
) 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: answerdotai/ModernBERT-base, Apache-2.0.
- Dataset: HuggingFaceFW/fineweb-edu-llama3-annotations, ODC-By 1.0; its texts come from FineWeb, also ODC-By, and Common Crawl's terms of use apply.
- Packages the tokenize step installs: Transformers, Tokenizers, Datasets, SentencePiece and the Hugging Face Hub client, Apache-2.0.