Fine-tune a vision-language model
Source on GitHub: the workflows/fine-tune-vision-language-model folder, with its README and its workflow file.
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 | cpu-4 |
| Fetch the base model | swaleio/hf-download | cpu-4 |
| Copy the image splits | swaleio/duckdb | cpu-4 |
Turn each image and its label into a prompt and an answer (prepare.py) | swaleio/python-3-13 | cpu-4 |
| Write the training config | swaleio/bash | cpu-4 |
| Fine-tune | swaleio/trl-sft | a100-1 |
| Write the eval requests, with each image inline | swaleio/duckdb | cpu-4 |
| Answer with the base model, and with the fine-tuned model | swaleio/vllm-batch | a100-1 each |
| Compare accuracy | swaleio/duckdb | 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.
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 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 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, Apache-2.0.
- Dataset: 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).