Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Swale example workflows

Ready-to-run [Swale](https://swale.io) workflows for the jobs machine-learning
teams run over and over: batch inference and labelling with an LLM, building
teams run over and over: batch inference and labeling with an LLM, building
datasets from documents, images and audio, fine-tuning and aligning models,
evaluating, merging, quantizing and serving them. Each workflow is a YAML file
built from the task definitions published by `swaleio` on Swale Hub, and splits
Expand Down Expand Up @@ -52,15 +52,15 @@ tools/check_workflows.py the check CI runs on every workflow

## Workflows

### Inference, labelling and evaluation with LLMs
### Inference, labeling and evaluation with LLMs

| Workflow | What it does | GPU steps |
|----------|--------------|-----------|
| [generate-responses](workflows/generate-responses) | Answers every prompt in a dataset with a chat model, as Parquet | vLLM batch |
| [label-text](workflows/label-text) | Labels texts with one of a fixed set of labels and measures agreement | vLLM batch |
| [classify-images](workflows/classify-images) | Labels images with a vision-language model and measures agreement | vLLM batch |
| [detect-objects](workflows/detect-objects) | Finds objects as bounding boxes with a vision-language model | vLLM batch |
| [caption-video](workflows/caption-video) | Captions a video frame by frame and summarises it | vLLM batch |
| [caption-video](workflows/caption-video) | Captions a video frame by frame and summarizes it | vLLM batch |
| [ocr-pages](workflows/ocr-pages) | Transcribes a PDF page by page with a vision-language model | vLLM batch |
| [synthetic-reasoning-data](workflows/synthetic-reasoning-data) | Builds a chain-of-thought dataset, judged against references | vLLM batch |
| [llm-as-a-judge](workflows/llm-as-a-judge) | Scores a model's answers from 1 to 10 with a judge model | vLLM batch |
Expand Down Expand Up @@ -90,8 +90,8 @@ tools/check_workflows.py the check CI runs on every workflow
| [dpo-alignment](workflows/dpo-alignment) | Aligns a model with DPO and measures its win rate with a judge | TRL DPO, vLLM batch |
| [kto-alignment](workflows/kto-alignment) | Aligns a model with KTO and measures its win rate with a judge | TRL KTO, vLLM batch |
| [reward-model](workflows/reward-model) | Trains a reward model and scores held-out preference pairs | TRL reward |
| [grpo-math](workflows/grpo-math) | Trains maths reasoning with GRPO and a checked reward | TRL GRPO, lm-eval |
| [rloo-math](workflows/rloo-math) | Trains maths reasoning with RLOO and a checked reward | TRL RLOO, lm-eval |
| [grpo-math](workflows/grpo-math) | Trains math reasoning with GRPO and a checked reward | TRL GRPO, lm-eval |
| [rloo-math](workflows/rloo-math) | Trains math reasoning with RLOO and a checked reward | TRL RLOO, lm-eval |
| [distill-model](workflows/distill-model) | Distills a larger model into a smaller one | TRL distillation, lm-eval |
| [vlm-finetune](workflows/vlm-finetune) | Fine-tunes a vision-language model and compares accuracy | TRL SFT, vLLM batch |

Expand All @@ -101,7 +101,7 @@ tools/check_workflows.py the check CI runs on every workflow
|----------|--------------|-----------|
| [merge-models](workflows/merge-models) | Merges two fine-tunes with mergekit and scores all three | lm-eval |
| [quantize-and-pick](workflows/quantize-and-pick) | Quantizes to several presets and keeps the smallest good one | llama.cpp |
| [score-gguf](workflows/score-gguf) | Scores a GGUF model's maths answers on a CPU, with parallel clients | none by default |
| [score-gguf](workflows/score-gguf) | Scores a GGUF model's math answers on a CPU, with parallel clients | none by default |

### Training task-specific models with scripts

Expand All @@ -111,7 +111,7 @@ tools/check_workflows.py the check CI runs on every workflow
| [text-regression](workflows/text-regression) | Fine-tunes an encoder to predict a number per text | training, prediction |
| [token-classification](workflows/token-classification) | Fine-tunes an encoder to tag named entities | training, tagging |
| [extractive-qa](workflows/extractive-qa) | Fine-tunes a model to find answers in long documents | training, scoring tokens |
| [summarization](workflows/summarization) | Fine-tunes a sequence-to-sequence model to summarise | training, generation |
| [summarization](workflows/summarization) | Fine-tunes a sequence-to-sequence model to summarize | training, generation |
| [translation](workflows/translation) | Fine-tunes a translation model | training, generation |
| [sentence-embeddings](workflows/sentence-embeddings) | Fine-tunes a sentence-embedding model for retrieval | training, embedding |
| [setfit-classifier](workflows/setfit-classifier) | Trains a few-shot classifier with SetFit | training, prediction |
Expand Down
4 changes: 2 additions & 2 deletions workflows/caption-video/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Describes a video in words. FFmpeg takes one frame every few seconds, a
vision-language model writes a one-sentence caption of each frame, and the same
model then reads the timed captions and summarises the whole video in a
model then reads the timed captions and summarizes the whole video in a
paragraph.

| Step | Task definition | Compute |
Expand All @@ -12,7 +12,7 @@ paragraph.
| Write one caption request per frame, with the frame inline | `swaleio/duckdb` | `cpu-4` |
| Caption the frames | `swaleio/vllm-batch` | `a100-1` |
| Join captions to their times, write the summary request | `swaleio/duckdb` | `cpu-4` |
| Summarise the video | `swaleio/vllm-batch` | `a100-1` |
| Summarize the video | `swaleio/vllm-batch` | `a100-1` |
| Write the summary out and print it | `swaleio/duckdb` | `cpu-4` |

Every step is its own task.
Expand Down
8 changes: 4 additions & 4 deletions workflows/caption-video/workflow.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,13 @@ blocks:
'messages': [{'role': 'user', 'content':
'These are captions of frames from one video, with the second each frame is from:\n' ||
string_agg(second || 's: ' || caption, '\n' ORDER BY frame) ||
'\n\nSummarise what happens in the video in a short paragraph.'}],
'\n\nSummarize what happens in the video in a short paragraph.'}],
'max_tokens': 256, 'temperature': 0} AS body
FROM captions
) TO '${{env.WORKFLOW_STORAGE}}/summary-request.jsonl' (FORMAT json);

summarise:
name: Summarise video
summarize:
name: Summarize video
uses: swaleio/vllm-batch
compute_type: a100-1
start_on:
Expand All @@ -116,7 +116,7 @@ blocks:
name: Show summary
uses: swaleio/duckdb
start_on:
- summarise
- summarize
args:
sql: |
COPY (SELECT response.body.choices[1].message.content AS summary
Expand Down
4 changes: 2 additions & 2 deletions workflows/classify-images/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ labels, a last step measures agreement and prints a confusion table.
| Measure agreement with existing labels, when `gold_column` is set | `swaleio/duckdb` | `cpu-4` |
| Upload to the Hugging Face Hub, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` |

Every step is its own task; only labelling holds a GPU.
Every step is its own task; only labeling holds a GPU.

For a specialised task, a small model asked cold may label poorly. Use a larger
For a specialized task, a small model asked cold may label poorly. Use a larger
model, or fine-tune one with the
[image classification](../image-classification) workflow.

Expand Down
6 changes: 3 additions & 3 deletions workflows/classify-images/workflow.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,13 @@ blocks:
- label
args:
sql: |
CREATE TABLE labelled AS
CREATE TABLE labeled AS
SELECT i.*, trim(r.response.body.choices[1].message.content) AS llm_label
FROM '${{env.WORKFLOW_STORAGE}}/images.parquet' i
JOIN read_json('${{env.WORKFLOW_STORAGE}}/results.jsonl') r USING (custom_id)
ORDER BY custom_id;
SELECT llm_label, count(*) AS images FROM labelled GROUP BY ALL ORDER BY images DESC;
COPY labelled TO '${{env.WORKFLOW_STORAGE}}/labels.parquet' (FORMAT parquet);
SELECT llm_label, count(*) AS images FROM labeled GROUP BY ALL ORDER BY images DESC;
COPY labeled TO '${{env.WORKFLOW_STORAGE}}/labels.parquet' (FORMAT parquet);

compare:
name: Compare when existing labels are given
Expand Down
2 changes: 1 addition & 1 deletion workflows/distill-model/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Distill a larger model into a smaller one

Teaches a small model to behave like a larger one of the same family on your
prompts. The student answers maths prompts and learns to match the teacher's
prompts. The student answers math prompts and learns to match the teacher's
word-by-word distribution over the answer; the student is scored on GSM8K's
test split before and after.

Expand Down
2 changes: 1 addition & 1 deletion workflows/distill-model/workflow.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: Distill a larger model into a smaller one
description: Distills a larger teacher into a smaller student of the same family on maths prompts with TRL, and compares the student's GSM8K score before and after.
description: Distills a larger teacher into a smaller student of the same family on math prompts with TRL, and compares the student's GSM8K score before and after.
compute_type: cpu-4

inputs:
Expand Down
2 changes: 1 addition & 1 deletion workflows/dpo-alignment/workflow.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ blocks:
args:
sql: |
-- Each pair is judged with the aligned answer first on even rows and second on odd
-- rows, so a judge that prefers one position does not favour either model.
-- rows, so a judge that prefers one position does not favor either model.
CREATE TABLE pairs AS
SELECT p.custom_id, p.prompt,
b.response.body.choices[1].message.content AS base,
Expand Down
2 changes: 1 addition & 1 deletion workflows/entity-extraction/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Extract named entities with GLiNER

Finds named entities of the types you name, such as people, organisations,
Finds named entities of the types you name, such as people, organizations,
places and dates, in a collection of texts, with GLiNER. GLiNER takes the types
as plain words when it runs, so there is nothing to train. The texts are split
into shards that several CPU tasks read at the same time, and SQL gathers what
Expand Down
2 changes: 1 addition & 1 deletion workflows/extractive-qa/preprocess.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Turns question and context pairs into overlapping token windows for extractive QA, on a CPU.

A context longer than one window is split into several, overlapping by --stride
tokens. Training windows are labelled with the answer's start and end token,
tokens. Training windows are labeled with the answer's start and end token,
or with the first token when the answer is not inside the window. Evaluation
windows keep each token's character offsets in the context, so answers can be
read back out of the text later.
Expand Down
8 changes: 4 additions & 4 deletions workflows/extractive-qa/score.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Scores predicted answers with exact match and token F1, on a CPU, with the standard library only.

Both compare normalised text: lower case, without punctuation, articles or
Both compare normalized text: lower case, without punctuation, articles or
extra spaces. A question with several reference answers takes the best score
over them.
"""
Expand All @@ -12,14 +12,14 @@
from collections import Counter


def normalise(text):
def normalize(text):
text = "".join(ch for ch in text.lower() if ch not in set(string.punctuation))
text = re.sub(r"\b(a|an|the)\b", " ", text)
return " ".join(text.split())


def f1(prediction, reference):
predicted, gold = normalise(prediction).split(), normalise(reference).split()
predicted, gold = normalize(prediction).split(), normalize(reference).split()
common = sum((Counter(predicted) & Counter(gold)).values())
if not predicted or not gold:
return float(predicted == gold)
Expand All @@ -40,7 +40,7 @@ def main():
for line in f:
row = json.loads(line)
references = row["answers"]["text"]
exact += max(float(normalise(row["prediction"]) == normalise(r)) for r in references)
exact += max(float(normalize(row["prediction"]) == normalize(r)) for r in references)
overlap += max(f1(row["prediction"], r) for r in references)
count += 1
scores = {"questions": count, "exact_match": round(100 * exact / count, 2), "f1": round(100 * overlap / count, 2)}
Expand Down
2 changes: 1 addition & 1 deletion workflows/extractive-qa/train.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Fine-tunes an extractive question-answering model on labelled windows, on a GPU.
"""Fine-tunes an extractive question-answering model on labeled windows, on a GPU.

The training loop is the one step of the workflow that stays a single script:
it holds the model, the optimizer and the batches together on one GPU.
Expand Down
6 changes: 3 additions & 3 deletions workflows/grpo-math/README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# Train maths reasoning with GRPO
# Train math reasoning with GRPO

Trains a model to solve maths word problems with group relative policy
Trains a model to solve math word problems with group relative policy
optimization. For each question the model writes several answers;
TRL's `accuracy_reward` gives 1 to the answers whose final result matches the
reference, checked with `math-verify`, and the model learns to favour them. The
reference, checked with `math-verify`, and the model learns to favor them. The
base model and the trained model are both scored on GSM8K's test split.

| Step | Task definition | Compute |
Expand Down
4 changes: 2 additions & 2 deletions workflows/grpo-math/workflow.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: Train maths reasoning with GRPO
description: Trains a model on maths word problems with TRL's GRPO, rewarding answers that match the reference, and compares its GSM8K score before and after.
name: Train math reasoning with GRPO
description: Trains a model on math word problems with TRL's GRPO, rewarding answers that match the reference, and compares its GSM8K score before and after.
compute_type: cpu-4

inputs:
Expand Down
4 changes: 2 additions & 2 deletions workflows/image-classification/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@

Fine-tunes a vision transformer to put images into classes, here bean leaves
into healthy, angular leaf spot and bean rust, and measures it on held-out
images. Checking, resizing and normalising the images runs on a CPU, so the
images. Checking, resizing and normalizing the images runs on a CPU, so the
GPU is held only for training and prediction.

| 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 each label | `swaleio/duckdb` | `cpu-4` |
| Decode, check, resize and normalise every image ([`preprocess.py`](preprocess.py)) | `swaleio/python-3-13` | `cpu-4` |
| Decode, check, resize and normalize every image ([`preprocess.py`](preprocess.py)) | `swaleio/python-3-13` | `cpu-4` |
| Train ([`train.py`](train.py)) | `swaleio/transformers` | `a100-1` |
| Predict the eval split ([`predict.py`](predict.py)) | `swaleio/transformers` | `a100-1` |
| Compute accuracy, per-class F1 and macro F1 | `swaleio/duckdb` | `cpu-4` |
Expand Down
4 changes: 2 additions & 2 deletions workflows/image-classification/preprocess.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""Checks, resizes and normalises images for a vision model, on a CPU.
"""Checks, resizes and normalizes images for a vision model, on a CPU.

Every image is decoded and checked; one that cannot be decoded is dropped and
counted. The rest are converted to RGB, resized to the model's input size and
normalised with the model's own mean and standard deviation, read from its
normalized with the model's own mean and standard deviation, read from its
preprocessor_config.json. Each split is written as one file of float32 pixel
arrays, its labels and its shape, which the training task memory-maps, so it
spends its GPU time training.
Expand Down
2 changes: 1 addition & 1 deletion workflows/image-classification/workflow.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ blocks:
ORDER BY split DESC, label;

check_images:
name: Check, resize and normalise the images
name: Check, resize and normalize the images
uses: swaleio/python-3-13
start_on:
- fetch_scripts
Expand Down
2 changes: 1 addition & 1 deletion workflows/image-regression/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ expression over the dataset's columns to predict something else.
| Fetch this repository's scripts at `examples_ref` | `swaleio/git-clone` | `cpu-4` |
| Fetch the model | `swaleio/hf-download` | `cpu-4` |
| Prepare the splits and compute the target, print its range | `swaleio/duckdb` | `cpu-4` |
| Decode, check, resize and normalise every image ([`preprocess.py`](../image-classification/preprocess.py)) | `swaleio/python-3-13` | `cpu-4` |
| Decode, check, resize and normalize every image ([`preprocess.py`](../image-classification/preprocess.py)) | `swaleio/python-3-13` | `cpu-4` |
| Train with one output and a mean-squared-error loss ([`train.py`](../image-classification/train.py) `--regression`) | `swaleio/transformers` | `a100-1` |
| Predict the eval split ([`predict.py`](../image-classification/predict.py)) | `swaleio/transformers` | `a100-1` |
| Compute mean absolute error, root mean squared error, correlation and exact counts | `swaleio/duckdb` | `cpu-4` |
Expand Down
2 changes: 1 addition & 1 deletion workflows/image-regression/workflow.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ blocks:
FROM '${{env.WORKFLOW_STORAGE}}/eval.parquet';

check_images:
name: Check, resize and normalise the images
name: Check, resize and normalize the images
uses: swaleio/python-3-13
start_on:
- fetch_scripts
Expand Down
4 changes: 2 additions & 2 deletions workflows/kto-alignment/workflow.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: Align a model with KTO
description: Aligns a chat model to answers labelled good or bad with TRL's KTO, then measures its win rate against the base model on held-out prompts with a judge model.
description: Aligns a chat model to answers labeled good or bad with TRL's KTO, then measures its win rate against the base model on held-out prompts with a judge model.
compute_type: cpu-4

inputs:
Expand Down Expand Up @@ -129,7 +129,7 @@ blocks:
args:
sql: |
-- Each pair is judged with the aligned answer first on even rows and second on odd
-- rows, so a judge that prefers one position does not favour either model.
-- rows, so a judge that prefers one position does not favor either model.
CREATE TABLE pairs AS
SELECT p.custom_id, p.prompt,
b.response.body.choices[1].message.content AS base,
Expand Down
4 changes: 2 additions & 2 deletions workflows/label-text/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ and prints a confusion table.
| Step | Task definition | Compute |
|------|-----------------|---------|
| Fetch the model | `swaleio/hf-download` | `cpu-4` |
| Write one labelling request per text | `swaleio/duckdb` | `cpu-4` |
| Write one labeling request per text | `swaleio/duckdb` | `cpu-4` |
| Label | `swaleio/vllm-batch` | `a100-1` |
| Join labels to texts, count each label, write Parquet | `swaleio/duckdb` | `cpu-4` |
| Measure agreement with existing labels, when `gold_column` is set | `swaleio/duckdb` | `cpu-4` |
| Upload to the Hugging Face Hub, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` |

Every step is its own task; only labelling holds a GPU.
Every step is its own task; only labeling holds a GPU.

## Inputs

Expand Down
6 changes: 3 additions & 3 deletions workflows/label-text/workflow.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,13 @@ blocks:
- label
args:
sql: |
CREATE TABLE labelled AS
CREATE TABLE labeled AS
SELECT t.*, trim(r.response.body.choices[1].message.content) AS llm_label
FROM '${{env.WORKFLOW_STORAGE}}/texts.parquet' t
JOIN read_json('${{env.WORKFLOW_STORAGE}}/results.jsonl') r USING (custom_id)
ORDER BY custom_id;
SELECT llm_label, count(*) AS texts FROM labelled GROUP BY ALL ORDER BY texts DESC;
COPY labelled TO '${{env.WORKFLOW_STORAGE}}/labels.parquet' (FORMAT parquet);
SELECT llm_label, count(*) AS texts FROM labeled GROUP BY ALL ORDER BY texts DESC;
COPY labeled TO '${{env.WORKFLOW_STORAGE}}/labels.parquet' (FORMAT parquet);

compare:
name: Compare when existing labels are given
Expand Down
2 changes: 1 addition & 1 deletion workflows/llm-as-a-judge/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Run it on two models to compare them, or before and after a fine-tune.
| Answer | `swaleio/vllm-batch` | `a100-1` |
| Join answers to prompts, write one judge request per answer | `swaleio/duckdb` | `cpu-4` |
| Judge | `swaleio/vllm-batch` | `a100-1` |
| Summarise the scores | `swaleio/duckdb` | `cpu-4` |
| Summarize the scores | `swaleio/duckdb` | `cpu-4` |

Every step is its own task. vLLM's structured outputs hold the judge to a
number from 1 to 10, and its thinking is turned off, so it answers at once.
Expand Down
Loading
Loading