# Fine-tune a vision transformer for image regression

> **About this page**
>
> - Kind: Example
> - Summary: Fine-tunes a vision transformer to predict a number for each image, here how many objects are annotated in it, with error measures computed in SQL.
> - Last changed: 2026-12-03
> - Page: https://docs.swale.io/examples/image-regression
> - 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/image-regression`](https://github.com/swaleio/examples/tree/main/workflows/image-regression) folder, with its [README](https://github.com/swaleio/examples/blob/main/workflows/image-regression/README.md) and its [workflow file](https://github.com/swaleio/examples/blob/main/workflows/image-regression/workflow.yaml).

Fine-tunes a vision transformer to predict a number for each image. The default
target is the number of objects annotated in each picture of a construction-site
dataset, a simple way to count without drawing boxes; set `target` to any SQL
expression over the dataset's columns to predict something else.

| 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 and compute the target, print its range | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `cpu-4` |
| Decode, check, resize and normalize every image ([`preprocess.py`](https://github.com/swaleio/examples/blob/main/workflows/image-classification/preprocess.py)) | [`swaleio/python-3-13`](https://hub.swale.io/swaleio/python-3-13) | `cpu-4` |
| Train with one output and a mean-squared-error loss ([`train.py`](https://github.com/swaleio/examples/blob/main/workflows/image-classification/train.py) `--regression`) | [`swaleio/transformers`](https://hub.swale.io/swaleio/transformers) | `a100-1` |
| Predict the eval split ([`predict.py`](https://github.com/swaleio/examples/blob/main/workflows/image-classification/predict.py)) | [`swaleio/transformers`](https://hub.swale.io/swaleio/transformers) | `a100-1` |
| Compute mean absolute error, root mean squared error, correlation and exact counts | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `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.

The scripts are the [image classification](https://docs.swale.io/examples/image-classification.md)
workflow's, run with `--regression`.

**What stays one script:** the training loop, which holds the model, the
optimizer and the batches together on one GPU.

## Inputs

| Input | Default | Description |
|-------|---------|-------------|
| `model` | `google/vit-base-patch16-224-in21k` | Image model to fine-tune. |
| `train_data`, `eval_data` | the train and validation splits of `keremberke/construction-safety-object-detection` | Parquet files or globs with a Hugging Face Image column, as DuckDB paths. |
| `image_column` | `image` | The Image column. |
| `target` | `len(objects.category)` | SQL expression giving the number to predict. |
| `epochs` | `10` | 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, the predictions in
`predictions.parquet`, and the error measures 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 vision transformer for image regression
description: Fine-tunes a vision transformer to predict a number for each image, here how many objects are annotated in it, with error measures computed in SQL.
compute_type: cpu-4

inputs:
  model:
    description: Hugging Face repo id of the image model to fine-tune.
    default: google/vit-base-patch16-224-in21k
  train_data:
    description: Parquet file or glob of training images with a Hugging Face Image column, as a DuckDB path.
    default: hf://datasets/keremberke/construction-safety-object-detection@~parquet/full/train/*.parquet
  eval_data:
    description: Parquet file or glob of evaluation images, as a DuckDB path.
    default: hf://datasets/keremberke/construction-safety-object-detection@~parquet/full/validation/*.parquet
  image_column:
    description: Image column, a struct holding the encoded image in its bytes field.
    default: image
  target:
    description: SQL expression over the dataset's columns that gives the number to predict; the default counts the annotated objects.
    default: len(objects.category)
  epochs:
    description: Training epochs.
    default: "10"
  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 {'bytes': "${{inputs.image_column}}".bytes} AS image, (${{inputs.target}})::DOUBLE AS label
                  FROM '${{inputs.train_data}}')
              TO '${{env.WORKFLOW_STORAGE}}/train.parquet' (FORMAT parquet);
            COPY (SELECT {'bytes': "${{inputs.image_column}}".bytes} AS image, (${{inputs.target}})::DOUBLE AS label
                  FROM '${{inputs.eval_data}}')
              TO '${{env.WORKFLOW_STORAGE}}/eval.parquet' (FORMAT parquet);
            SELECT 'train' AS split, count(*) AS images, round(avg(label), 2) AS mean, min(label) AS min, max(label) AS max
              FROM '${{env.WORKFLOW_STORAGE}}/train.parquet'
            UNION ALL
            SELECT 'eval', count(*), round(avg(label), 2), min(label), max(label)
              FROM '${{env.WORKFLOW_STORAGE}}/eval.parquet';

      check_images:
        name: Check, resize and normalize the images
        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-images.txt"], check=True)
            subprocess.run([sys.executable, f"{examples}/workflows/image-classification/preprocess.py",
                            "--model", f"{storage}/base-model", "--label-type", "float",
                            "--train", f"{storage}/train.parquet", "--eval", f"{storage}/eval.parquet",
                            "--output", f"{storage}/prepared"],
                           env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True)

      train:
        name: Train
        uses: swaleio/transformers
        compute_type: a100-1
        start_on:
          - check_images
        args:
          script: |
            import os, subprocess, sys

            storage = os.environ["WORKFLOW_STORAGE"]
            subprocess.run([sys.executable, f"{storage}/examples/workflows/image-classification/train.py",
                            "--model", f"{storage}/base-model", "--data", f"{storage}/prepared",
                            "--regression", "--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/image-classification/predict.py",
                            "--model", f"{storage}/model", "--data", f"{storage}/prepared/eval",
                            "--output", f"{storage}/predictions.parquet"], check=True)

      score:
        name: Score
        uses: swaleio/duckdb
        start_on:
          - predict
        args:
          sql: |
            COPY (
              SELECT count(*) AS rows,
                     round(avg(abs(prediction - label)), 3) AS mean_absolute_error,
                     round(sqrt(avg((prediction - label) ^ 2)), 3) AS root_mean_squared_error,
                     round(corr(prediction, label), 4) AS pearson,
                     round(avg((round(prediction) = label)::INT), 4) AS exact_count
              FROM '${{env.WORKFLOW_STORAGE}}/predictions.parquet'
            ) 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

- Model: [google/vit-base-patch16-224-in21k](https://huggingface.co/google/vit-base-patch16-224-in21k), Apache-2.0.
- Dataset: [keremberke/construction-safety-object-detection](https://huggingface.co/datasets/keremberke/construction-safety-object-detection), CC BY 4.0.
- Packages the image step installs: NumPy (BSD-3-Clause), Pillow (MIT-CMU) and PyArrow (Apache-2.0).
