Fine-tune a model for extractive question answering
Source on GitHub: the workflows/extractive-question-answering folder, with its README and its workflow file.
Fine-tunes a question-answering model to find the span of a document that answers a question, here on long COVID-19 research papers, starting from a model already trained on SQuAD. Documents are much longer than the model's window, so each is split into overlapping windows; after prediction, the best span across a question's windows is its answer.
| 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 |
| Split questions into train and eval by document | swaleio/duckdb | cpu-4 |
Split contexts into overlapping windows, label answer positions (preprocess.py) | swaleio/python-3-13 | cpu-4 |
Train (train.py) | swaleio/transformers | a100-1 |
Score every token of every eval window as a start and an end (predict.py) | swaleio/transformers | a100-1 |
Pick each question's answer from its windows (postprocess.py) | swaleio/python-3-13 | cpu-4 |
Score exact match and F1 (score.py) | swaleio/python-3-13 | 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.
What stays one script: the training loop, which holds the model, the optimizer and the batches together on one GPU. Picking answers and scoring use only Python's standard library.
Inputs
| Input | Default | Description |
|---|---|---|
model | distilbert/distilbert-base-cased-distilled-squad | Question-answering model to fine-tune. |
data | deepset/covid_qa_deepset | Parquet file or glob of questions in SQuAD form, as a DuckDB path. |
eval_every | 10 | One document in this many is held out, with its questions. |
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, each eval question's answer
and references in answers.jsonl, and exact match and F1 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 a model for extractive question answering
description: Fine-tunes a question-answering model on a GPU to find answers inside long documents, with windowing, answer picking, exact match and F1 on CPUs.
compute_type: cpu-4
inputs:
model:
description: Hugging Face repo id of the question-answering model to fine-tune.
default: distilbert/distilbert-base-cased-distilled-squad
data:
description: Parquet file or glob of questions in SQuAD form (id, question, context, answers), as a DuckDB path.
default: hf://datasets/deepset/covid_qa_deepset@~parquet/covid_qa_deepset/train/*.parquet
eval_every:
description: One document in this many is held out for evaluation, with all its questions.
default: "10"
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: |
-- Questions about one document stay in the same split, so evaluation reads
-- documents the model never saw.
CREATE TABLE questions AS
SELECT id::VARCHAR AS id, question, context, answers, document_id
FROM '${{inputs.data}}' WHERE len(answers.text) > 0;
COPY (SELECT * EXCLUDE (document_id) FROM questions WHERE document_id % ${{inputs.eval_every}} <> 0)
TO '${{env.WORKFLOW_STORAGE}}/train.parquet' (FORMAT parquet);
COPY (SELECT * EXCLUDE (document_id) FROM questions WHERE document_id % ${{inputs.eval_every}} = 0)
TO '${{env.WORKFLOW_STORAGE}}/eval.parquet' (FORMAT parquet);
COPY (SELECT id, context, answers FROM questions WHERE document_id % ${{inputs.eval_every}} = 0)
TO '${{env.WORKFLOW_STORAGE}}/eval-examples.jsonl' (FORMAT json);
SELECT document_id % ${{inputs.eval_every}} = 0 AS held_out, count(DISTINCT document_id) AS documents,
count(*) AS questions, round(avg(length(context))) AS mean_context_characters
FROM questions GROUP BY ALL ORDER BY held_out;
tokenize:
name: Split contexts into windows
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/extractive-question-answering/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/extractive-question-answering/train.py",
"--model", f"{storage}/base-model", "--data", f"{storage}/tokenized",
"--epochs", "${{inputs.epochs}}", "--output", f"{storage}/model"], check=True)
predict:
name: Score answer tokens
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/extractive-question-answering/predict.py",
"--model", f"{storage}/model", "--data", f"{storage}/tokenized/eval",
"--output", f"{storage}/window-scores.jsonl"], check=True)
postprocess:
name: Pick the answers
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/extractive-question-answering/postprocess.py",
"--scores", f"{storage}/window-scores.jsonl",
"--examples", f"{storage}/eval-examples.jsonl",
"--output", f"{storage}/answers.jsonl"], check=True)
score:
name: Score
uses: swaleio/python-3-13
start_on:
- postprocess
args:
script: |
import os, subprocess, sys
storage = os.environ["WORKFLOW_STORAGE"]
subprocess.run([sys.executable, f"{storage}/examples/workflows/extractive-question-answering/score.py",
"--answers", f"{storage}/answers.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
- Model: distilbert/distilbert-base-cased-distilled-squad, Apache-2.0.
- Dataset: deepset/covid_qa_deepset, Apache-2.0.
- Packages the windowing step installs: Transformers, Tokenizers, Datasets, SentencePiece and the Hugging Face Hub client, Apache-2.0.