Fine-tune an object detection model
Source on GitHub: the workflows/object-detection folder, with its README and its workflow file.
Fine-tunes an object detector, RT-DETRv2, to find and box chosen kinds of objects, here safety equipment and machinery on construction sites. The annotations are checked and converted to COCO format on a CPU; the detector trains and detects on a GPU; and the detections are scored with COCO mean average precision, and drawn on sample images, on a CPU.
| Step | Task definition | Compute |
|---|---|---|
Fetch this repository's scripts at examples_ref | swaleio/git-clone | cpu-4 |
| Fetch the model | swaleio/hf-download | cpu-4 |
| Prepare the splits, count boxes per category | swaleio/duckdb | cpu-4 |
Drop boxes with no area or outside their image, write COCO annotations (check_annotations.py) | swaleio/python-3-13 | cpu-4 |
Train (train.py) | swaleio/transformers | a100-1 |
Detect in the eval images (predict.py) | swaleio/transformers | a100-1 |
Score mean average precision (score.py), and draw sample detections (draw.py) | swaleio/python-3-13 | cpu-4 each |
Upload the detector, 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.
What stays one script: the training loop, which holds the model, the optimizer and the batches together on one GPU. The image processor resizes each image and turns its boxes into training targets inside it, on the fly.
Inputs
| Input | Default | Description |
|---|---|---|
model | PekingU/rtdetr_v2_r18vd | Object detector to fine-tune. |
train_data, eval_data | the train and validation splits of keremberke/construction-safety-object-detection | Parquet files or globs with image_id, image and objects (bbox as x, y, width, height, and category), as DuckDB paths. |
categories | the dataset's 17 categories | Category names in category-number order. |
epochs | 30 | 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 detector to. |
The download and the upload read the secret hf_token.
Output
The fine-tuned detector in model/ on the workspace, the detections in
detections.json, the scores in metrics.json, and drawn samples in
samples/.
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 an object detection model
description: Fine-tunes an object detector on annotated images on a GPU, with annotation checks, COCO conversion, mean average precision and sample drawings on CPUs.
compute_type: cpu-4
inputs:
model:
description: Hugging Face repo id of the object detector to fine-tune.
default: PekingU/rtdetr_v2_r18vd
train_data:
description: Parquet file or glob of training images, with image_id, image and objects (bbox, category) columns, 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
categories:
description: Category names, separated by commas, in category-number order.
default: barricade,dumpster,excavators,gloves,hardhat,mask,no-hardhat,no-mask,no-safety vest,person,safety net,safety shoes,safety vest,dump truck,mini-van,truck,wheel loader
epochs:
description: Training epochs.
default: "30"
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 detector 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 image_id, image, objects FROM '${{inputs.train_data}}')
TO '${{env.WORKFLOW_STORAGE}}/train.parquet' (FORMAT parquet);
COPY (SELECT image_id, image, objects FROM '${{inputs.eval_data}}')
TO '${{env.WORKFLOW_STORAGE}}/eval.parquet' (FORMAT parquet);
SELECT string_split($$${{inputs.categories}}$$, ',')[category + 1] AS category, count(*) AS boxes
FROM (SELECT unnest(objects.category) AS category FROM '${{env.WORKFLOW_STORAGE}}/train.parquet')
GROUP BY ALL ORDER BY boxes DESC;
check:
name: Check the annotations, convert to COCO
uses: swaleio/python-3-13
start_on:
- fetch_scripts
- 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-detection.txt"], check=True)
subprocess.run([sys.executable, f"{examples}/workflows/object-detection/check_annotations.py",
"--splits", f"train={storage}/train.parquet", f"eval={storage}/eval.parquet",
"--categories", "${{inputs.categories}}", "--output", storage],
env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True)
train:
name: Train
uses: swaleio/transformers
compute_type: a100-1
start_on:
- fetch_model
- check
args:
script: |
import os, subprocess, sys
storage = os.environ["WORKFLOW_STORAGE"]
examples = f"{storage}/examples"
subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "--no-deps", "--target", "/tmp/deps",
"-r", f"{examples}/requirements/gpu-detection.txt"], check=True)
subprocess.run([sys.executable, f"{examples}/workflows/object-detection/train.py",
"--model", f"{storage}/base-model", "--train", f"{storage}/train.parquet",
"--coco", f"{storage}/train.coco.json", "--categories", "${{inputs.categories}}",
"--epochs", "${{inputs.epochs}}", "--output", f"{storage}/model"],
env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True)
predict:
name: Detect in the eval images
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/object-detection/predict.py",
"--model", f"{storage}/model", "--images", f"{storage}/eval.parquet",
"--output", f"{storage}/detections.json"], check=True)
score:
name: Score mean average precision
uses: swaleio/python-3-13
start_on:
- predict
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-detection.txt"], check=True)
subprocess.run([sys.executable, f"{examples}/workflows/object-detection/score.py",
"--coco", f"{storage}/eval.coco.json", "--detections", f"{storage}/detections.json",
"--output", f"{storage}/metrics.json"],
env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True)
draw:
name: Draw sample detections
uses: swaleio/python-3-13
start_on:
- predict
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-detection.txt"], check=True)
subprocess.run([sys.executable, f"{examples}/workflows/object-detection/draw.py",
"--images", f"{storage}/eval.parquet", "--detections", f"{storage}/detections.json",
"--coco", f"{storage}/eval.coco.json", "--output", f"{storage}/samples"],
env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True)
publish:
name: Upload when asked
start_on:
- score
- draw
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: PekingU/rtdetr_v2_r18vd, Apache-2.0.
- Dataset: keremberke/construction-safety-object-detection, CC BY 4.0.
- Packages the CPU steps install: pycocotools (BSD-2-Clause), NumPy (BSD-3-Clause), PyArrow (Apache-2.0) and Pillow (MIT-CMU).
- Package the training step installs: SciPy (BSD-3-Clause).