Skip to main content

Fine-tune an encoder for token classification

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

Fine-tunes an encoder model to tag named entities, word by word, and scores it the way named-entity recognition is usually scored: an entity counts only when its type and its exact span of words are right. The default data is WIESP 2022, entities such as instruments, missions and organizations in astrophysics papers.

StepTask definitionCompute
Fetch this repository's scripts at examples_refswaleio/git-clonecpu-4
Fetch the modelswaleio/hf-downloadcpu-4
Prepare the splits, count the most frequent entity typesswaleio/duckdbcpu-4
Tokenize and align each word's tag to its first sub-word token (preprocess.py)swaleio/python-3-13cpu-4
Train (train.py)swaleio/transformersa100-1
Tag the eval split (predict.py)swaleio/transformersa100-1
Score entities: precision, recall and F1, overall and per type (score.py)swaleio/python-3-13cpu-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, which holds the model, the optimizer and the batches together on one GPU. The scorer uses only Python's standard library.

Inputs​

InputDefaultDescription
modelgoogle-bert/bert-base-casedEncoder model whose tokenizer accepts text split into words.
train_data, eval_datathe train and validation splits of adsabs/WIESP2022-NERParquet files or globs, as DuckDB paths.
tokens_columntokensColumn holding each sentence as a list of words.
tags_columnner_tagsColumn holding the IOB2 tags, such as B-Telescope.
epochs4Training 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, each sentence's gold and predicted tags in predictions.jsonl, and the scores 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.

  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 token classification
description: Fine-tunes an encoder model to tag named entities word by word, with tag alignment on a CPU, training and tagging on a GPU, and entity-level F1 on a CPU.
compute_type: cpu-4

inputs:
model:
description: Hugging Face repo id of the encoder model to fine-tune; its tokenizer must accept text already split into words.
default: google-bert/bert-base-cased
train_data:
description: Parquet file or glob of training sentences, as a DuckDB path.
default: hf://datasets/adsabs/WIESP2022-NER/data/train-00000-of-00001.parquet
eval_data:
description: Parquet file or glob of evaluation sentences, as a DuckDB path.
default: hf://datasets/adsabs/WIESP2022-NER/data/validation-00000-of-00001.parquet
tokens_column:
description: Column holding each sentence as a list of words.
default: tokens
tags_column:
description: Column holding each sentence's IOB2 tags, one per word, as text such as B-Person.
default: ner_tags
epochs:
description: Training epochs.
default: "4"
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.tokens_column}}" AS tokens, "${{inputs.tags_column}}" AS tags FROM '${{inputs.train_data}}')
TO '${{env.WORKFLOW_STORAGE}}/train.parquet' (FORMAT parquet);
COPY (SELECT "${{inputs.tokens_column}}" AS tokens, "${{inputs.tags_column}}" AS tags FROM '${{inputs.eval_data}}')
TO '${{env.WORKFLOW_STORAGE}}/eval.parquet' (FORMAT parquet);
-- The most frequent entity types in the training split.
SELECT substr(tag, 3) AS entity, count(*) AS mentions
FROM (SELECT unnest(tags) AS tag FROM '${{env.WORKFLOW_STORAGE}}/train.parquet')
WHERE tag LIKE 'B-%' GROUP BY ALL ORDER BY mentions DESC LIMIT 15;

tokenize:
name: Tokenize and align tags
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/token-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/token-classification/train.py",
"--model", f"{storage}/base-model", "--data", f"{storage}/tokenized",
"--epochs", "${{inputs.epochs}}", "--output", f"{storage}/model"], check=True)

predict:
name: Tag 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/token-classification/predict.py",
"--model", f"{storage}/model", "--data", f"{storage}/tokenized/eval",
"--output", f"{storage}/predictions.jsonl"], check=True)

score:
name: Score entities
uses: swaleio/python-3-13
start_on:
- predict
args:
script: |
import os, subprocess, sys

storage = os.environ["WORKFLOW_STORAGE"]
subprocess.run([sys.executable, f"{storage}/examples/workflows/token-classification/score.py",
"--predictions", f"{storage}/predictions.jsonl",
"--output", f"{storage}/metrics.json"], check=True)

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​