Skip to main content

Fine-tune a model to write news summaries

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

Fine-tunes a sequence-to-sequence model, such as Flan-T5, to summarize news articles, then generates a summary of every held-out article and scores the summaries with ROUGE. Generating needs a GPU; scoring does not, so the two are separate tasks.

StepTask definitionCompute
Fetch this repository's scripts at examples_refswaleio/git-clonecpu-4
Fetch the modelswaleio/hf-downloadcpu-4
Prepare the splits, print the mean article and summary lengthsswaleio/duckdbcpu-4
Tokenize articles and summaries (preprocess.py)swaleio/python-3-13cpu-4
Train (train.py)swaleio/transformersa100-1
Generate a summary of each eval article, with beam search (generate.py)swaleio/transformersa100-1
Score ROUGE-1, ROUGE-2 and ROUGE-L (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.

These scripts also serve the translation workflow.

Inputs​

InputDefaultDescription
modelgoogle/flan-t5-smallSequence-to-sequence model to fine-tune.
train_data, eval_datathe train and validation splits of abisee/cnn_dailymail 3.0.0Parquet files or globs, as DuckDB paths.
source_column, target_columnarticle, highlightsColumns holding each article and its reference summary.
train_rows, eval_rows10000, 500Rows to use from each.
prefixsummarize: Text put before every article, as T5 models expect.
epochs1Training 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 eval article's reference and generated summary in predictions.parquet, and the ROUGE 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 a model to write news summaries
description: Fine-tunes a sequence-to-sequence model to summarize news articles, with tokenizing on a CPU, training and generation on a GPU, and ROUGE computed on a CPU.
compute_type: cpu-4

inputs:
model:
description: Hugging Face repo id of the sequence-to-sequence model to fine-tune.
default: google/flan-t5-small
train_data:
description: Parquet file or glob of training articles, as a DuckDB path.
default: hf://datasets/abisee/cnn_dailymail/3.0.0/train-00000-of-00003.parquet
eval_data:
description: Parquet file or glob of evaluation articles, as a DuckDB path.
default: hf://datasets/abisee/cnn_dailymail/3.0.0/validation-00000-of-00001.parquet
source_column:
description: Column holding each text to summarize.
default: article
target_column:
description: Column holding each reference summary.
default: highlights
train_rows:
description: Training articles to use.
default: "10000"
eval_rows:
description: Evaluation articles to use.
default: "500"
prefix:
description: Text put before every source, as the model expects.
default: "summarize: "
epochs:
description: Training epochs.
default: "1"
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.source_column}}" AS source, "${{inputs.target_column}}" AS target
FROM '${{inputs.train_data}}' LIMIT ${{inputs.train_rows}})
TO '${{env.WORKFLOW_STORAGE}}/train.parquet' (FORMAT parquet);
COPY (SELECT "${{inputs.source_column}}" AS source, "${{inputs.target_column}}" AS target
FROM '${{inputs.eval_data}}' LIMIT ${{inputs.eval_rows}})
TO '${{env.WORKFLOW_STORAGE}}/eval.parquet' (FORMAT parquet);
SELECT count(*) AS train_rows,
round(avg(length(source))) AS mean_source_characters,
round(avg(length(target))) AS mean_summary_characters
FROM '${{env.WORKFLOW_STORAGE}}/train.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/summarization/preprocess.py",
"--model", f"{storage}/base-model", "--prefix", "${{inputs.prefix}}",
"--source-max-length", "512", "--target-max-length", "128",
"--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/summarization/train.py",
"--model", f"{storage}/base-model", "--data", f"{storage}/tokenized",
"--epochs", "${{inputs.epochs}}", "--learning-rate", "3e-4",
"--output", f"{storage}/model"], check=True)

generate:
name: Generate for 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/summarization/generate.py",
"--model", f"{storage}/model", "--eval", f"{storage}/eval.parquet",
"--prefix", "${{inputs.prefix}}", "--source-max-length", "512",
"--max-new-tokens", "128", "--output", f"{storage}/predictions.parquet"], check=True)

score:
name: Score
uses: swaleio/python-3-13
start_on:
- generate
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-score-rouge.txt"], check=True)
subprocess.run([sys.executable, f"{examples}/workflows/summarization/score.py",
"--predictions", f"{storage}/predictions.parquet", "--metric", "rouge",
"--output", f"{storage}/metrics.json"],
env={**os.environ, "PYTHONPATH": "/tmp/deps"}, 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: google/flan-t5-small, Apache-2.0.
  • Dataset: abisee/cnn_dailymail, Apache-2.0.
  • Packages the steps install: Transformers, Tokenizers, Datasets, SentencePiece and the Hugging Face Hub client to tokenize, and rouge-score (with absl-py, NLTK and NumPy) and PyArrow to score, all under permissive licenses (Apache-2.0 and BSD).