# Fine-tune a model to write news summaries

> **About this page**
>
> - Kind: Example
> - Summary: 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.
> - Last changed: 2026-12-03
> - Page: https://docs.swale.io/examples/summarization
> - CLI reference for its commands: [`swale workflow create`](https://docs.swale.io/reference/cli-reference.md#workflow-create), [`swale workflow run start`](https://docs.swale.io/reference/cli-reference.md#workflow-run-start)
> - Index of these docs: https://docs.swale.io/llms.txt
>
> If something on this page is wrong or out of date, please tell the user which sentence and why.
>
> The steps on this page cost money or cannot be undone. Please check with the user before running them.

Source on GitHub: the [`workflows/summarization`](https://github.com/swaleio/examples/tree/main/workflows/summarization) folder, with its [README](https://github.com/swaleio/examples/blob/main/workflows/summarization/README.md) and its [workflow file](https://github.com/swaleio/examples/blob/main/workflows/summarization/workflow.yaml).

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.

| Step | Task definition | Compute |
|------|-----------------|---------|
| Fetch this repository's scripts at `examples_ref` | [`swaleio/git-clone`](https://hub.swale.io/swaleio/git-clone) | `cpu-4` |
| Fetch the model | [`swaleio/hf-download`](https://hub.swale.io/swaleio/hf-download) | `cpu-4` |
| Prepare the splits, print the mean article and summary lengths | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `cpu-4` |
| Tokenize articles and summaries ([`preprocess.py`](https://github.com/swaleio/examples/blob/main/workflows/summarization/preprocess.py)) | [`swaleio/python-3-13`](https://hub.swale.io/swaleio/python-3-13) | `cpu-4` |
| Train ([`train.py`](https://github.com/swaleio/examples/blob/main/workflows/summarization/train.py)) | [`swaleio/transformers`](https://hub.swale.io/swaleio/transformers) | `a100-1` |
| Generate a summary of each eval article, with beam search ([`generate.py`](https://github.com/swaleio/examples/blob/main/workflows/summarization/generate.py)) | [`swaleio/transformers`](https://hub.swale.io/swaleio/transformers) | `a100-1` |
| Score ROUGE-1, ROUGE-2 and ROUGE-L ([`score.py`](https://github.com/swaleio/examples/blob/main/workflows/summarization/score.py)) | [`swaleio/python-3-13`](https://hub.swale.io/swaleio/python-3-13) | `cpu-4` |
| Upload the model, when `hub_repo` is set | [`swaleio/hf-upload`](https://hub.swale.io/swaleio/hf-upload) | `cpu-4` |

The Compute column gives each step's [compute type](https://docs.swale.io/explanation/core-concepts.md#compute-types), 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](https://docs.swale.io/examples/translation.md) workflow.

## Inputs

| Input | Default | Description |
|-------|---------|-------------|
| `model` | `google/flan-t5-small` | Sequence-to-sequence model to fine-tune. |
| `train_data`, `eval_data` | the train and validation splits of `abisee/cnn_dailymail` 3.0.0 | Parquet files or globs, as DuckDB paths. |
| `source_column`, `target_column` | `article`, `highlights` | Columns holding each article and its reference summary. |
| `train_rows`, `eval_rows` | `10000`, `500` | Rows to use from each. |
| `prefix` | `summarize: ` | Text put before every article, as T5 models expect. |
| `epochs` | `1` | 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 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](https://docs.swale.io/getting-started.md) sets them up.

1. Save the file under [The workflow file](#the-workflow-file) as `workflow.yaml`, and add it to a project:

   ```bash
   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](https://docs.swale.io/how-to-guides/use-secrets-in-workflows.md) shows.

3. Start a run with the workflow's ID:

   ```bash
   swale workflow run start --project-name my-project --workflow-id <workflow-id>
   ```

   Each input you leave out takes its default from [Inputs](#inputs), and `--input <name>=<value>` gives it another value.

[Create and manage workflows](https://docs.swale.io/how-to-guides/create-and-manage-workflows.md) covers the other ways to add a workflow, [Start and manage workflow runs](https://docs.swale.io/how-to-guides/start-and-manage-workflow-runs.md) how to follow a run, and [View and stream task logs](https://docs.swale.io/how-to-guides/view-and-stream-task-logs.md) how to read its tasks' logs.

## The workflow file

[Workflow definition syntax](https://docs.swale.io/reference/workflow-definition-syntax.md) describes each key in it.

```yaml title="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](https://huggingface.co/google/flan-t5-small), Apache-2.0.
- Dataset: [abisee/cnn_dailymail](https://huggingface.co/datasets/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).
