# Fine-tune a vision-language model

> **About this page**
>
> - Kind: Example
> - Summary: Fine-tunes a small vision-language model with TRL to answer a question about images, then compares its accuracy with the base model's on held-out images.
> - Last changed: 2026-12-03
> - Page: https://docs.swale.io/examples/fine-tune-vision-language-model
> - 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/fine-tune-vision-language-model`](https://github.com/swaleio/examples/tree/main/workflows/fine-tune-vision-language-model) folder, with its [README](https://github.com/swaleio/examples/blob/main/workflows/fine-tune-vision-language-model/README.md) and its [workflow file](https://github.com/swaleio/examples/blob/main/workflows/fine-tune-vision-language-model/workflow.yaml).

Teaches a small vision-language model to answer a question about images, here
which disease a bean leaf shows, with TRL's supervised fine-tuning. Then the
base model and the fine-tuned model both answer the held-out images through
vLLM, held to the label names, and their accuracy is compared.

| 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 base model | [`swaleio/hf-download`](https://hub.swale.io/swaleio/hf-download) | `cpu-4` |
| Copy the image splits | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `cpu-4` |
| Turn each image and its label into a prompt and an answer ([`prepare.py`](https://github.com/swaleio/examples/blob/main/workflows/fine-tune-vision-language-model/prepare.py)) | [`swaleio/python-3-13`](https://hub.swale.io/swaleio/python-3-13) | `cpu-4` |
| Write the training config | [`swaleio/bash`](https://hub.swale.io/swaleio/bash) | `cpu-4` |
| Fine-tune | [`swaleio/trl-sft`](https://hub.swale.io/swaleio/trl-sft) | `a100-1` |
| Write the eval requests, with each image inline | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `cpu-4` |
| Answer with the base model, and with the fine-tuned model | [`swaleio/vllm-batch`](https://hub.swale.io/swaleio/vllm-batch) | `a100-1` each |
| Compare accuracy | [`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.

Every step is its own task; training uses the `trl-sft` definition, which
trains vision-language models when the data holds images. The base model
answers while the other one trains.

## Inputs

| Input | Default | Description |
|-------|---------|-------------|
| `model` | `HuggingFaceTB/SmolVLM-256M-Instruct` | Vision-language model to fine-tune; all of its weights are trained. |
| `train_data`, `eval_data` | the train and test splits of `AI-Lab-Makerere/beans` | Parquet files or globs with a Hugging Face Image column and a label column, as DuckDB paths. |
| `labels` | `angular_leaf_spot,bean_rust,healthy` | Label names in label-number order. |
| `question` | a question about the leaf | What is asked about every image. |
| `epochs` | `3` | 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, the training and the upload read the secret `hf_token`.

## Output

The fine-tuned model in `model/` on the workspace, both models' answers in
`answers-base.jsonl` and `answers-tuned.jsonl`, and the comparison in the last
task's log.

## 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-language model
description: Fine-tunes a small vision-language model with TRL to answer a question about images, then compares its accuracy with the base model's on held-out images.
compute_type: cpu-4

inputs:
  model:
    description: Hugging Face repo id of the vision-language model to fine-tune. All of its weights are trained.
    default: HuggingFaceTB/SmolVLM-256M-Instruct
  train_data:
    description: Parquet file or glob of training images with a Hugging Face Image column and a label column, as a DuckDB path.
    default: hf://datasets/AI-Lab-Makerere/beans/data/train-00000-of-00001.parquet
  eval_data:
    description: Parquet file or glob of evaluation images, as a DuckDB path.
    default: hf://datasets/AI-Lab-Makerere/beans/data/test-00000-of-00001.parquet
  labels:
    description: Label names, separated by commas, in label-number order; the model learns to answer with them.
    default: angular_leaf_spot,bean_rust,healthy
  question:
    description: The question asked about every image.
    default: What does this bean leaf show? Answer angular_leaf_spot, bean_rust or healthy.
  epochs:
    description: Training epochs.
    default: "3"
  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 base model
        uses: swaleio/hf-download
        args:
          repo: ${{inputs.model}}
          dest: ${{env.WORKFLOW_STORAGE}}/base-model
          token: ${{secrets.hf_token}}

      copy_data:
        name: Copy the image splits
        uses: swaleio/duckdb
        args:
          sql: |
            COPY (SELECT * FROM '${{inputs.train_data}}') TO '${{env.WORKFLOW_STORAGE}}/train-images.parquet' (FORMAT parquet);
            COPY (SELECT row_number() OVER () - 1 AS id, * FROM '${{inputs.eval_data}}')
              TO '${{env.WORKFLOW_STORAGE}}/eval-images.parquet' (FORMAT parquet);
            SELECT (SELECT count(*) FROM '${{env.WORKFLOW_STORAGE}}/train-images.parquet') AS train_images,
                   (SELECT count(*) FROM '${{env.WORKFLOW_STORAGE}}/eval-images.parquet') AS eval_images;

      prepare:
        name: Turn images into chat rows
        uses: swaleio/python-3-13
        start_on:
          - fetch_scripts
          - copy_data
        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-chat-images.txt"], check=True)
            subprocess.run([sys.executable, f"{examples}/workflows/fine-tune-vision-language-model/prepare.py",
                            "--data", f"{storage}/train-images.parquet", "--labels", "${{inputs.labels}}",
                            "--question", """${{inputs.question}}""", "--output", f"{storage}/train-chat.parquet"],
                           env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True)

      write_config:
        name: Write training config
        uses: swaleio/bash
        args:
          script: |
            cat > "$WORKFLOW_STORAGE/sft.yaml" <<EOF
            model_name_or_path: ${{inputs.model}}
            datasets:
              - path: parquet
                data_files: $WORKFLOW_STORAGE/train-chat.parquet
                split: train
            learning_rate: 5.0e-5
            num_train_epochs: ${{inputs.epochs}}
            per_device_train_batch_size: 8
            gradient_accumulation_steps: 2
            max_length: null
            bf16: true
            report_to: none
            save_strategy: "no"
            output_dir: $WORKFLOW_STORAGE/model
            EOF

      train:
        name: Fine-tune
        uses: swaleio/trl-sft
        compute_type: a100-1
        start_on:
          - prepare
          - write_config
        args:
          config: ${{env.WORKFLOW_STORAGE}}/sft.yaml
          token: ${{secrets.hf_token}}

      requests:
        name: Write the eval requests
        uses: swaleio/duckdb
        start_on:
          - copy_data
        args:
          sql: |
            CREATE TABLE prompts AS
              SELECT 'img-' || lpad(id::VARCHAR, 5, '0') AS custom_id,
                     [{'role': 'user', 'content': [
                       {'type': 'image_url', 'image_url': {'url': 'data:image/jpeg;base64,' || base64(image.bytes)}},
                       {'type': 'text', 'text': $$${{inputs.question}}$$}]}] AS messages
              FROM '${{env.WORKFLOW_STORAGE}}/eval-images.parquet';
            COPY (SELECT custom_id, 'POST' AS method, '/v1/chat/completions' AS url,
                         {'model': '${{env.WORKFLOW_STORAGE}}/base-model', 'messages': messages, 'max_tokens': 16, 'temperature': 0,
                          'structured_outputs': {'choice': string_split($$${{inputs.labels}}$$, ',')}} AS body FROM prompts)
              TO '${{env.WORKFLOW_STORAGE}}/requests-base.jsonl' (FORMAT json);
            COPY (SELECT custom_id, 'POST' AS method, '/v1/chat/completions' AS url,
                         {'model': '${{env.WORKFLOW_STORAGE}}/model', 'messages': messages, 'max_tokens': 16, 'temperature': 0,
                          'structured_outputs': {'choice': string_split($$${{inputs.labels}}$$, ',')}} AS body FROM prompts)
              TO '${{env.WORKFLOW_STORAGE}}/requests-tuned.jsonl' (FORMAT json);

      answer_base:
        name: Answer with the base model
        uses: swaleio/vllm-batch
        compute_type: a100-1
        start_on:
          - fetch_model
          - requests
        args:
          model: ${{env.WORKFLOW_STORAGE}}/base-model
          input_file: ${{env.WORKFLOW_STORAGE}}/requests-base.jsonl
          output_file: ${{env.WORKFLOW_STORAGE}}/answers-base.jsonl

      answer_tuned:
        name: Answer with the fine-tuned model
        uses: swaleio/vllm-batch
        compute_type: a100-1
        start_on:
          - train
          - requests
        args:
          model: ${{env.WORKFLOW_STORAGE}}/model
          input_file: ${{env.WORKFLOW_STORAGE}}/requests-tuned.jsonl
          output_file: ${{env.WORKFLOW_STORAGE}}/answers-tuned.jsonl

      compare:
        name: Compare accuracy
        uses: swaleio/duckdb
        start_on:
          - answer_base
          - answer_tuned
        args:
          sql: |
            CREATE TABLE gold AS
              SELECT 'img-' || lpad(id::VARCHAR, 5, '0') AS custom_id,
                     string_split($$${{inputs.labels}}$$, ',')[labels + 1] AS label
              FROM '${{env.WORKFLOW_STORAGE}}/eval-images.parquet';
            CREATE TABLE answers AS
              SELECT 'base' AS model, custom_id, trim(response.body.choices[1].message.content) AS answer
                FROM read_json('${{env.WORKFLOW_STORAGE}}/answers-base.jsonl')
              UNION ALL
              SELECT 'fine-tuned', custom_id, trim(response.body.choices[1].message.content)
                FROM read_json('${{env.WORKFLOW_STORAGE}}/answers-tuned.jsonl');
            SELECT a.model, count(*) AS images, round(avg((a.answer = g.label)::INT), 4) AS accuracy
              FROM answers a JOIN gold g USING (custom_id) GROUP BY a.model ORDER BY a.model;

      publish:
        name: Upload when asked
        start_on:
          - compare
        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: [HuggingFaceTB/SmolVLM-256M-Instruct](https://huggingface.co/HuggingFaceTB/SmolVLM-256M-Instruct), Apache-2.0.
- Dataset: [AI-Lab-Makerere/beans](https://huggingface.co/datasets/AI-Lab-Makerere/beans), MIT.
- Packages the prepare step installs: Datasets, the Hugging Face Hub client and PyArrow (Apache-2.0) and Pillow (MIT-CMU).
