Skip to main content

Fine-tune an encoder for text classification

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

Fine-tunes an encoder model, such as ModernBERT, to put texts into classes, and measures it on held-out rows. The work is split so that only training and prediction hold a GPU: the splits are prepared with SQL, tokenizing runs on a CPU, and the scores are computed with SQL.

StepTask definitionCompute
Fetch this repository's scripts at examples_refswaleio/git-clonecpu-4
Fetch the modelswaleio/hf-downloadcpu-4
Prepare the train and eval splits, count each labelswaleio/duckdbcpu-4
Tokenize both splits (preprocess.py)swaleio/python-3-13cpu-4
Train (train.py)swaleio/transformersa100-1
Predict the eval split (predict.py)swaleio/transformersa100-1
Compute accuracy, per-class F1 and macro F1swaleio/duckdbcpu-4
Upload the model, when hub_repo is setswaleio/hf-uploadcpu-4

The Compute column gives each step's compute type, the compute its tasks are allocated.

What stays one script: the training loop, in train.py. The model, the optimizer and the batches live together on one GPU for the whole of training, so it cannot be cut into tasks.

Inputs​

InputDefaultDescription
modelanswerdotai/ModernBERT-baseEncoder model to fine-tune.
train_data, eval_datathe train and validation splits of google-research-datasets/poem_sentimentParquet files or globs, as DuckDB paths.
text_columnverse_textColumn holding the text.
label_columnlabelColumn holding the label, as a number from 0.
labelsnegative,positive,no_impact,mixedLabel names in label-number order.
epochs5Training epochs.
examples_refmainBranch, tag or full commit SHA of this repository whose scripts run.
hub_repoemptyHugging 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 metrics.json with the 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.

  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: Fine-tune an encoder for text classification
description: Fine-tunes an encoder model to classify text, with tokenizing on a CPU, training and prediction on a GPU, and accuracy and macro F1 computed 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/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
epochs:
description: Training epochs.
default: "5"
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.label_column}}"::BIGINT AS label FROM '${{inputs.train_data}}')
TO '${{env.WORKFLOW_STORAGE}}/train.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 'train' AS split, label, count(*) AS rows FROM '${{env.WORKFLOW_STORAGE}}/train.parquet' GROUP BY ALL
UNION ALL
SELECT 'eval', label, count(*) FROM '${{env.WORKFLOW_STORAGE}}/eval.parquet' GROUP BY ALL
ORDER BY split DESC, label;

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",
"--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",
"--labels", "${{inputs.labels}}", "--epochs", "${{inputs.epochs}}",
"--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: |
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​