diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6313b56 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml new file mode 100644 index 0000000..2e774ef --- /dev/null +++ b/.github/workflows/check.yml @@ -0,0 +1,36 @@ +name: Check workflows + +# Checks every example workflow against the task definitions on the catalog's +# main branch: keys, compute types, the inputs each task passes, and that every +# script compiles. + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + check: + name: Check workflows against the catalog + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 + + - name: Check out the task-definition catalog + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 + with: + repository: swaleio/task-definitions + path: catalog + + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.13" + + - name: Install the checker's dependencies + run: python -m pip install -r tools/requirements.txt + + - name: Check workflows + run: python tools/check_workflows.py --catalog catalog diff --git a/README.md b/README.md index 0ce272b..5e063d8 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,133 @@ -# examples -Swale's example workflow definitions +# 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 +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 +its job into separate tasks, so a run's graph shows each step, its logs and its +outputs, and only the steps that need a GPU hold one. + +Some workflows also run short Python scripts kept next to them in this +repository. Those workflows clone this repository at the branch, tag or full +commit SHA their `examples_ref` input names, `main` by default; pin a commit's +full SHA to keep a workflow's scripts fixed. + +## Running a workflow + +1. Clone this repository, or download a workflow's `workflow.yaml`, and add it + to a project with the CLI or with **Add Workflow → Upload File** in the app: + + ```sh + swale workflow create --project-name my-project --file workflows/generate-responses/workflow.yaml + ``` + + **Import from GitHub** reads only repositories on GitHub accounts that the + Swale GitHub App is installed on and that your GitHub user can access, so it + cannot read this repository. To import a workflow from GitHub instead, fork + this repository to such an account and import it from your fork. + +2. Workflows that download gated models or upload to the Hugging Face Hub read + a secret named `hf_token`; uploading needs a token with write access. Every + upload step runs only when its `hub_repo` input is set. + +3. Start a run, overriding any input: + + ```sh + swale workflow run start --project-name my-project --workflow-id --input limit=50 + ``` + +The [Swale documentation](https://docs.swale.io) covers workflows, task +definitions and compute types. + +## Layout + +``` +workflows//workflow.yaml the workflow +workflows//README.md what it does, its steps, inputs, outputs and licenses +workflows//*.py the scripts it runs, if any +requirements/*.txt the pinned packages scripts install +tools/check_workflows.py the check CI runs on every workflow +``` + +## Workflows + +### Inference, labelling 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 | +| [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 | + +### Datasets from documents, images, audio and text + +| Workflow | What it does | GPU steps | +|----------|--------------|-----------| +| [pdfs-to-markdown](workflows/pdfs-to-markdown) | Converts PDFs to a Markdown dataset with Docling, one task per PDF | none | +| [scans-to-text](workflows/scans-to-text) | Reads scanned pages with Tesseract, one task per scan | none | +| [transcribe-audio](workflows/transcribe-audio) | Transcribes audio or video files with whisper.cpp, one task per file | whisper.cpp | +| [speech-dataset](workflows/speech-dataset) | Builds a speech-recognition dataset of transcribed clips | whisper.cpp | +| [dataset-statistics](workflows/dataset-statistics) | Profiles, filters, deduplicates and re-packs a Parquet dataset | none | +| [embed-dataset](workflows/embed-dataset) | Embeds every row with Text Embeddings Inference and parallel clients | TEI | +| [retrieval-index](workflows/retrieval-index) | Builds a RAG index from PDFs and answers a test query | TEI | +| [semantic-dedup](workflows/semantic-dedup) | Drops rows that mean nearly the same | vLLM batch | +| [entity-extraction](workflows/entity-extraction) | Extracts named entities of types you name with GLiNER | none | +| [web-text-curation](workflows/web-text-curation) | Filters and deduplicates web text with datatrove | none | + +### Training and aligning language models + +| Workflow | What it does | GPU steps | +|----------|--------------|-----------| +| [finetune-evaluate-quantize](workflows/finetune-evaluate-quantize) | Fine-tunes, evaluates, converts to GGUF, quantizes and publishes | TRL SFT, lm-eval | +| [compare-finetunes](workflows/compare-finetunes) | Fine-tunes twice with different settings and compares scores | TRL SFT, lm-eval | +| [train-then-serve](workflows/train-then-serve) | Fine-tunes a model and serves it with vLLM in the same run | TRL SFT, vLLM | +| [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 | +| [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 | + +### Merging, quantizing and serving + +| Workflow | What it does | GPU steps | +|----------|--------------|-----------| +| [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 | + +### Training task-specific models with scripts + +| Workflow | What it does | GPU steps | +|----------|--------------|-----------| +| [text-classification](workflows/text-classification) | Fine-tunes an encoder to classify text | training, prediction | +| [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 | +| [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 | +| [image-classification](workflows/image-classification) | Fine-tunes a vision transformer to classify images | training, prediction | +| [image-regression](workflows/image-regression) | Fine-tunes a vision transformer to predict a number per image | training, prediction | +| [object-detection](workflows/object-detection) | Fine-tunes an object detector and scores its mAP | training, detection | +| [tabular](workflows/tabular) | Trains gradient-boosted trees on a table | none | + +Each workflow's README lists its steps, says which part stays one script and +why, and gives the licenses of its default model, data and the packages its +scripts install. + +## Licenses + +The workflows, scripts and tools in this repository are licensed under the +[MIT License](LICENSE). The models, datasets, documents and packages they use +keep their own licenses, listed in each workflow's README. Defaults are chosen +under licenses that allow commercial use; check the license of anything you put +in their place. diff --git a/requirements/cpu-chat-images.txt b/requirements/cpu-chat-images.txt new file mode 100644 index 0000000..c84cb68 --- /dev/null +++ b/requirements/cpu-chat-images.txt @@ -0,0 +1,5 @@ +# What vlm-finetune's step that writes chat rows installs into the python-3-13 task. +datasets==5.2.0 +huggingface_hub==2.5.0 +pillow==13.0.0 +pyarrow==26.0.1 diff --git a/requirements/cpu-datatrove.txt b/requirements/cpu-datatrove.txt new file mode 100644 index 0000000..61962a3 --- /dev/null +++ b/requirements/cpu-datatrove.txt @@ -0,0 +1,9 @@ +# What the web-text curation steps install into the python-3-13 task, with their +# dependencies. spaCy splits text into words for the quality rules; NLTK splits sentences. +datatrove==0.10.1 +nltk==3.10.4 +pyarrow==26.0.1 +tokenizers==0.23.3 +xxhash==3.6.0 +numpy==2.5.5 +spacy==3.8.18 diff --git a/requirements/cpu-detection.txt b/requirements/cpu-detection.txt new file mode 100644 index 0000000..43069c4 --- /dev/null +++ b/requirements/cpu-detection.txt @@ -0,0 +1,5 @@ +# What the object-detection CPU steps install into the python-3-13 task. +pycocotools==2.0.11 +numpy==2.5.5 +pyarrow==26.0.1 +pillow==13.0.0 diff --git a/requirements/cpu-gliner.txt b/requirements/cpu-gliner.txt new file mode 100644 index 0000000..b833647 --- /dev/null +++ b/requirements/cpu-gliner.txt @@ -0,0 +1,10 @@ +# What the GLiNER step installs into the python-3-13 task, with their dependencies. +# GLiNER 0.2.30 accepts Transformers below 5.23, so this step installs its own copy +# of the stack, with the CPU build of PyTorch, rather than using the GPU image. +--extra-index-url https://download.pytorch.org/whl/cpu +torch==2.14.1+cpu +transformers==5.22.2 +gliner==0.2.30 +pyarrow==26.0.1 +# GLiNER's encoder tokenizer converts from SentencePiece, which needs protobuf. +protobuf==7.36.2 diff --git a/requirements/cpu-images.txt b/requirements/cpu-images.txt new file mode 100644 index 0000000..dc2e780 --- /dev/null +++ b/requirements/cpu-images.txt @@ -0,0 +1,4 @@ +# What the CPU image preprocessing steps install into the python-3-13 task. +numpy==2.5.5 +pillow==13.0.0 +pyarrow==26.0.1 diff --git a/requirements/cpu-numpy.txt b/requirements/cpu-numpy.txt new file mode 100644 index 0000000..e7a35c0 --- /dev/null +++ b/requirements/cpu-numpy.txt @@ -0,0 +1,3 @@ +# What the semantic deduplication step installs into the python-3-13 task. +numpy==2.5.5 +pyarrow==26.0.1 diff --git a/requirements/cpu-score-bleu.txt b/requirements/cpu-score-bleu.txt new file mode 100644 index 0000000..55ca617 --- /dev/null +++ b/requirements/cpu-score-bleu.txt @@ -0,0 +1,3 @@ +# What the translation score step installs into the python-3-13 task. +sacrebleu==2.6.0 +pyarrow==26.0.1 diff --git a/requirements/cpu-score-rouge.txt b/requirements/cpu-score-rouge.txt new file mode 100644 index 0000000..144f744 --- /dev/null +++ b/requirements/cpu-score-rouge.txt @@ -0,0 +1,3 @@ +# What the summarization score step installs into the python-3-13 task. +rouge-score==0.1.2 +pyarrow==26.0.1 diff --git a/requirements/cpu-tabular.txt b/requirements/cpu-tabular.txt new file mode 100644 index 0000000..3092d84 --- /dev/null +++ b/requirements/cpu-tabular.txt @@ -0,0 +1,4 @@ +# What the tabular steps install into the python-3-13 task, with their dependencies. +scikit-learn==1.9.1 +pandas==3.1.1 +pyarrow==26.0.1 diff --git a/requirements/cpu-tokenize.txt b/requirements/cpu-tokenize.txt new file mode 100644 index 0000000..eaf86d1 --- /dev/null +++ b/requirements/cpu-tokenize.txt @@ -0,0 +1,8 @@ +# What the CPU preprocessing steps install into the python-3-13 task: the same +# versions the GPU training image runs, without PyTorch. SentencePiece reads the +# tokenizers of models such as Marian and T5. +transformers==5.24.1 +tokenizers==0.23.3 +datasets==5.2.0 +huggingface_hub==2.5.0 +sentencepiece==0.2.3 diff --git a/requirements/gpu-detection.txt b/requirements/gpu-detection.txt new file mode 100644 index 0000000..b6df2c2 --- /dev/null +++ b/requirements/gpu-detection.txt @@ -0,0 +1,4 @@ +# What the object detection training step installs, with pip --no-deps, next to +# the PyTorch and Transformers the transformers task already has: the detector's +# loss matches predicted boxes to true ones with SciPy. +scipy==1.18.1 diff --git a/requirements/gpu-sentence-transformers.txt b/requirements/gpu-sentence-transformers.txt new file mode 100644 index 0000000..0d422b0 --- /dev/null +++ b/requirements/gpu-sentence-transformers.txt @@ -0,0 +1,9 @@ +# What the sentence-transformers and SetFit GPU steps install, with pip --no-deps, +# next to the PyTorch, Transformers and Datasets the transformers task already has. +sentence-transformers==6.3.0 +scikit-learn==1.9.1 +scipy==1.18.1 +joblib==1.6.0 +threadpoolctl==3.8.0 +narwhals==2.30.0 +cloudpickle==3.1.3 diff --git a/requirements/gpu-setfit.txt b/requirements/gpu-setfit.txt new file mode 100644 index 0000000..0b5501b --- /dev/null +++ b/requirements/gpu-setfit.txt @@ -0,0 +1,4 @@ +# What the SetFit GPU steps install, with pip --no-deps, on top of +# gpu-sentence-transformers.txt. +setfit==1.2.0 +evaluate==0.4.6 diff --git a/tools/check_workflows.py b/tools/check_workflows.py new file mode 100644 index 0000000..c1b77cc --- /dev/null +++ b/tools/check_workflows.py @@ -0,0 +1,146 @@ +"""Checks every example workflow against the Swale task-definition catalog. + + python tools/check_workflows.py --catalog + +For each workflows//workflow.yaml it checks that the file parses, uses only +the keys the workflow syntax allows, names compute types Swale offers, and that +every task names a catalog definition without a version, passes only inputs that +definition declares and every input it requires, and runs a definition that needs +a GPU on a GPU compute type and a CPU definition on a CPU one. Every Python script +must compile, and every workflow directory needs a README.md. +""" + +import argparse +import re +import sys +from pathlib import Path + +import yaml + +COMPUTE_TYPES = {"cpu-2", "cpu-4", "cpu-16", "a100-1", "h100-1"} +GPU_TYPES = {"a100-1", "h100-1"} +WORKFLOW_KEYS = {"name", "description", "compute_type", "inputs", "blocks", "entry_point"} +TASK_KEYS = {"name", "uses", "compute_type", "start_on", "terminate_on", "args", "image_credentials", "if", "for_each"} +NAME_RE = re.compile(r"^[A-Za-z0-9 ._-]{1,100}$") +EXPR_RE = re.compile(r"\$\{\{\s*(.*?)\s*\}\}") + + +def load_definition(catalog, name): + path = Path(catalog) / "tasks" / name / "task.md" + if not path.is_file(): + return None + text = path.read_text(encoding="utf-8") + front = yaml.safe_load(text.split("---", 2)[1]) + compute = re.search(r"## Compute\s+\*\*(GPU required|GPU recommended|CPU)\.\*\*", text) + front["_compute"] = compute.group(1) if compute else None + return front + + +def check_workflow(path, catalog): + errors = [] + try: + wf = yaml.safe_load(path.read_text(encoding="utf-8")) + except yaml.YAMLError as e: + return [f"does not parse: {e}"] + unknown = set(wf) - WORKFLOW_KEYS + if unknown: + errors.append(f"unknown top-level keys {sorted(unknown)}") + if not NAME_RE.match(str(wf.get("name", ""))): + errors.append(f"name {wf.get('name')!r} must be 1-100 letters, numbers, spaces, '.', '_' or '-'") + default_compute = wf.get("compute_type") + if default_compute not in COMPUTE_TYPES: + errors.append(f"compute_type {default_compute!r} is not one Swale offers") + inputs = wf.get("inputs") or {} + blocks = wf.get("blocks") or {} + if wf.get("entry_point", "main") not in blocks: + errors.append(f"entry_point {wf.get('entry_point', 'main')!r} names no block") + all_tasks = {} + for block_name, block in blocks.items(): + for key, task in (block.get("tasks") or {}).items(): + if key in all_tasks: + errors.append(f"task key {key!r} is used twice") + all_tasks[key] = (block_name, task) + for key, (block_name, task) in all_tasks.items(): + where = f"task {key!r}" + unknown = set(task) - TASK_KEYS + if unknown: + errors.append(f"{where}: unknown keys {sorted(unknown)}") + if not task.get("name"): + errors.append(f"{where}: has no name") + block_tasks = blocks[block_name]["tasks"] + for dep_kind in ("start_on", "terminate_on"): + for dep in task.get(dep_kind) or []: + if dep not in block_tasks or dep == key: + errors.append(f"{where}: {dep_kind} names {dep!r}, which is not another task of its block") + compute = task.get("compute_type") or default_compute + if compute not in COMPUTE_TYPES: + errors.append(f"{where}: compute_type {compute!r} is not one Swale offers") + if "if" in task or "for_each" in task: + control = task.get("if") or task.get("for_each") + # YAML 1.1 reads the keys true and false as booleans. + branches = {str(k).lower(): v for k, v in control.items()} + targets = [branches.get("true"), branches.get("false")] if "if" in task else [control.get("block")] + for target in filter(None, targets): + if target not in blocks: + errors.append(f"{where}: names block {target!r}, which does not exist") + continue + uses = str(task.get("uses", "")) + m = re.match(r"^swaleio/([A-Za-z0-9_-]+)$", uses) + if not m: + errors.append(f"{where}: uses {uses!r} must be swaleio/ without a version") + continue + definition = load_definition(catalog, m.group(1)) + if definition is None: + errors.append(f"{where}: no catalog definition {m.group(1)!r}") + continue + declared = definition.get("inputs") or {} + args = task.get("args") or {} + for arg in args: + if arg not in declared: + errors.append(f"{where}: passes {arg!r}, which {uses} does not declare") + for name, spec in declared.items(): + spec = spec or {} + if spec.get("required") and not str(spec.get("default", "")).strip() and name not in args: + errors.append(f"{where}: does not pass {name!r}, which {uses} requires") + level = definition["_compute"] + if level == "GPU required" and compute not in GPU_TYPES: + errors.append(f"{where}: {uses} needs a GPU but runs on {compute}") + if level == "CPU" and compute in GPU_TYPES: + errors.append(f"{where}: {uses} runs on the CPU but holds {compute}") + for expr in EXPR_RE.findall(path.read_text(encoding="utf-8")): + for ref in re.findall(r"\binputs\.([A-Za-z0-9_-]+)", expr): + if ref not in inputs: + errors.append(f"expression {expr!r} reads undeclared input {ref!r}") + for ref in re.findall(r"\btasks\.([A-Za-z0-9_-]+)\.", expr): + if ref not in all_tasks: + errors.append(f"expression {expr!r} reads unknown task {ref!r}") + return errors + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--catalog", required=True, help="checkout of swaleio/task-definitions") + args = p.parse_args() + root = Path(__file__).resolve().parent.parent + failures = 0 + workflows = sorted((root / "workflows").glob("*/workflow.yaml")) + for path in workflows: + rel = path.relative_to(root) + for error in check_workflow(path, args.catalog): + print(f"::error file={rel}::{error}") + failures += 1 + if not (path.parent / "README.md").is_file(): + print(f"::error file={rel}::{path.parent.relative_to(root)} has no README.md") + failures += 1 + for script in sorted((root / "workflows").rglob("*.py")): + try: + compile(script.read_text(encoding="utf-8"), str(script), "exec") + except SyntaxError as e: + print(f"::error file={script.relative_to(root)},line={e.lineno}::{e.msg}") + failures += 1 + print(f"{len(workflows)} workflow(s) checked, {failures} problem(s).") + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/requirements.txt b/tools/requirements.txt new file mode 100644 index 0000000..f62ce0c --- /dev/null +++ b/tools/requirements.txt @@ -0,0 +1 @@ +PyYAML==6.0.3 diff --git a/workflows/caption-video/README.md b/workflows/caption-video/README.md new file mode 100644 index 0000000..e6b32fc --- /dev/null +++ b/workflows/caption-video/README.md @@ -0,0 +1,38 @@ +# Caption a video + +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 +paragraph. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Fetch the model | `swaleio/hf-download` | `cpu-4` | +| Extract one frame every `seconds_per_frame` seconds | `swaleio/ffmpeg` | `cpu-4` | +| 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` | +| Write the summary out and print it | `swaleio/duckdb` | `cpu-4` | + +Every step is its own task. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `video_url` | the Sintel trailer | URL or workspace path of the video; anything FFmpeg reads. | +| `seconds_per_frame` | `4` | Seconds between captioned frames. | +| `model` | `Qwen/Qwen2-VL-2B-Instruct` | Vision-language model on the Hub. | + +The download reads the secret `hf_token`. + +## Output + +`captions.parquet` on the workspace, with `frame`, `second` and `caption`, and +the summary in `summary.txt`. + +## Licenses of the defaults + +- Model: [Qwen/Qwen2-VL-2B-Instruct](https://huggingface.co/Qwen/Qwen2-VL-2B-Instruct), Apache-2.0. +- Video: the [Sintel](https://durian.blender.org) trailer, © Blender Foundation, CC BY 3.0. diff --git a/workflows/caption-video/workflow.yaml b/workflows/caption-video/workflow.yaml new file mode 100644 index 0000000..16de87a --- /dev/null +++ b/workflows/caption-video/workflow.yaml @@ -0,0 +1,125 @@ +name: Caption a video +description: Extracts frames from a video at a fixed interval, captions each one with a vision-language model, and writes a summary of the whole video from the captions. +compute_type: cpu-4 + +inputs: + video_url: + description: URL or workspace path of the video; anything FFmpeg reads. + default: https://download.blender.org/durian/trailer/sintel_trailer-480p.mp4 + seconds_per_frame: + description: Seconds between the frames that are captioned. + default: "4" + model: + description: Hub repo id of the vision-language model that captions. + default: Qwen/Qwen2-VL-2B-Instruct + +entry_point: main + +blocks: + main: + tasks: + fetch_model: + name: Fetch model + uses: swaleio/hf-download + args: + repo: ${{inputs.model}} + dest: ${{env.WORKFLOW_STORAGE}}/model + token: ${{secrets.hf_token}} + + frames: + name: Extract frames + uses: swaleio/ffmpeg + args: + script: | + set -euo pipefail + mkdir -p "$WORKFLOW_STORAGE/frames" + ffmpeg -hide_banner -loglevel error -i "${{inputs.video_url}}" \ + -vf "fps=1/${{inputs.seconds_per_frame}},scale=640:-2" -q:v 3 \ + "$WORKFLOW_STORAGE/frames/%04d.jpg" + ls "$WORKFLOW_STORAGE/frames" | wc -l + + requests: + name: Write caption requests + uses: swaleio/duckdb + start_on: + - frames + args: + sql: | + CREATE TABLE frames AS + SELECT regexp_extract(filename, '(\d+)\.jpg$', 1)::INT AS frame, + (frame - 1) * ${{inputs.seconds_per_frame}} AS second, + content + FROM read_blob('${{env.WORKFLOW_STORAGE}}/frames/*.jpg'); + COPY ( + SELECT 'frame-' || lpad(frame::VARCHAR, 4, '0') AS custom_id, + 'POST' AS method, '/v1/chat/completions' AS url, + {'model': '${{env.WORKFLOW_STORAGE}}/model', + 'messages': [{'role': 'user', 'content': [ + {'type': 'image_url', 'image_url': {'url': 'data:image/jpeg;base64,' || base64(content)}}, + {'type': 'text', 'text': 'Describe this video frame in one sentence.'}]}], + 'max_tokens': 96, 'temperature': 0} AS body + FROM frames + ) TO '${{env.WORKFLOW_STORAGE}}/caption-requests.jsonl' (FORMAT json); + COPY (SELECT frame, second FROM frames) TO '${{env.WORKFLOW_STORAGE}}/frames.parquet' (FORMAT parquet); + SELECT count(*) AS frames FROM frames; + + caption: + name: Caption frames + uses: swaleio/vllm-batch + compute_type: a100-1 + start_on: + - fetch_model + - requests + args: + model: ${{env.WORKFLOW_STORAGE}}/model + input_file: ${{env.WORKFLOW_STORAGE}}/caption-requests.jsonl + output_file: ${{env.WORKFLOW_STORAGE}}/captions.jsonl + + collect: + name: Collect captions + uses: swaleio/duckdb + start_on: + - caption + args: + sql: | + CREATE TABLE captions AS + SELECT f.frame, f.second, trim(c.response.body.choices[1].message.content) AS caption + FROM '${{env.WORKFLOW_STORAGE}}/frames.parquet' f + JOIN read_json('${{env.WORKFLOW_STORAGE}}/captions.jsonl') c + ON c.custom_id = 'frame-' || lpad(f.frame::VARCHAR, 4, '0') + ORDER BY f.frame; + COPY captions TO '${{env.WORKFLOW_STORAGE}}/captions.parquet' (FORMAT parquet); + SELECT second, caption FROM captions; + COPY ( + SELECT 'summary' AS custom_id, 'POST' AS method, '/v1/chat/completions' AS url, + {'model': '${{env.WORKFLOW_STORAGE}}/model', + '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.'}], + 'max_tokens': 256, 'temperature': 0} AS body + FROM captions + ) TO '${{env.WORKFLOW_STORAGE}}/summary-request.jsonl' (FORMAT json); + + summarise: + name: Summarise video + uses: swaleio/vllm-batch + compute_type: a100-1 + start_on: + - collect + args: + model: ${{env.WORKFLOW_STORAGE}}/model + input_file: ${{env.WORKFLOW_STORAGE}}/summary-request.jsonl + output_file: ${{env.WORKFLOW_STORAGE}}/summary.jsonl + + show: + name: Show summary + uses: swaleio/duckdb + start_on: + - summarise + args: + sql: | + COPY (SELECT response.body.choices[1].message.content AS summary + FROM read_json('${{env.WORKFLOW_STORAGE}}/summary.jsonl')) + TO '${{env.WORKFLOW_STORAGE}}/summary.txt' (FORMAT csv, HEADER false, QUOTE ''); + SELECT content AS summary FROM read_text('${{env.WORKFLOW_STORAGE}}/summary.txt'); diff --git a/workflows/classify-images/README.md b/workflows/classify-images/README.md new file mode 100644 index 0000000..15e19d5 --- /dev/null +++ b/workflows/classify-images/README.md @@ -0,0 +1,48 @@ +# Classify images with a vision-language model + +Labels every image in a dataset with one of a fixed set of labels by asking a +vision-language model about it, through vLLM's offline batch inference. Each +image travels inside its request as a base64 data URL, and vLLM's structured +outputs hold each answer to one of the labels. When the images already carry +labels, a last step measures agreement and prints a confusion table. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Fetch the model | `swaleio/hf-download` | `cpu-4` | +| Write one request per image, with the image inline | `swaleio/duckdb` | `cpu-4` | +| Label | `swaleio/vllm-batch` | `a100-1` | +| Join labels to the images' other columns, 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 Hub, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +Every step is its own task; only labelling holds a GPU. + +For a specialised task, a small model asked cold may label poorly. Use a larger +model, or fine-tune one with the +[image classification](../image-classification) workflow. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `model` | `Qwen/Qwen2-VL-2B-Instruct` | Vision-language model on the Hub that vLLM serves. | +| `images` | the test split of `AI-Lab-Makerere/beans` | Parquet file or glob with a Hugging Face Image column, as a DuckDB path. | +| `image_column` | `image` | The Image column: a struct whose `bytes` field holds the encoded image. | +| `image_type` | `image/jpeg` | Media type of the encoded images. | +| `labels` | `angular_leaf_spot,bean_rust,healthy` | Labels the model chooses from, separated by commas. | +| `instruction` | a question about bean leaves | What the model is asked about each image. | +| `gold_column` | `labels` | Column of existing labels, as positions in `labels` from 0; empty skips the comparison. | +| `limit` | `1000` | Number of images to label. | +| `hub_repo` | empty | Hub dataset repo to upload `labels.parquet` to. | + +The model download and the upload read the secret `hf_token`. + +## Output + +`labels.parquet` on the workspace: every column but the image, a `custom_id` +and the model's `llm_label`. + +## Licenses of the defaults + +- Model: [Qwen/Qwen2-VL-2B-Instruct](https://huggingface.co/Qwen/Qwen2-VL-2B-Instruct), Apache-2.0. +- Dataset: [AI-Lab-Makerere/beans](https://huggingface.co/datasets/AI-Lab-Makerere/beans), MIT. diff --git a/workflows/classify-images/workflow.yaml b/workflows/classify-images/workflow.yaml new file mode 100644 index 0000000..b94fba2 --- /dev/null +++ b/workflows/classify-images/workflow.yaml @@ -0,0 +1,141 @@ +name: Classify images with a vision-language model +description: Labels every image in a dataset with one of a fixed set of labels, using a vision-language model through vLLM batch inference, and measures agreement with existing labels. +compute_type: cpu-4 + +inputs: + model: + description: Hub repo id of the vision-language model that labels. + default: Qwen/Qwen2-VL-2B-Instruct + images: + description: Parquet file or glob holding the images in a Hugging Face Image column, as a DuckDB path such as hf://datasets///. + default: hf://datasets/AI-Lab-Makerere/beans/data/test-00000-of-00001.parquet + image_column: + description: Image column, a struct holding the encoded image in its bytes field. + default: image + image_type: + description: Media type of the encoded images. + default: image/jpeg + labels: + description: The labels to choose from, separated by commas. The model can answer only with one of them. + default: angular_leaf_spot,bean_rust,healthy + instruction: + description: What the model is asked about each image. + default: This is a photo of a bean plant leaf. Is it healthy, or does it show angular leaf spot or bean rust? Answer with angular_leaf_spot, bean_rust or healthy only. + gold_column: + description: Column holding existing labels, as each label's position in labels counting from 0, to measure agreement against. Leave empty when the images have none. + default: labels + limit: + description: Number of images to label. + default: "1000" + hub_repo: + description: Hub dataset repo to upload the labels to, as namespace/name. Leave empty to keep them on the workspace only. + default: "" + +entry_point: main + +blocks: + main: + tasks: + model: + name: Fetch model + uses: swaleio/hf-download + args: + repo: ${{inputs.model}} + dest: ${{env.WORKFLOW_STORAGE}}/model + token: ${{secrets.hf_token}} + + requests: + name: Write requests + uses: swaleio/duckdb + args: + sql: | + CREATE TABLE images AS + SELECT 'row-' || lpad((row_number() OVER () - 1)::VARCHAR, 6, '0') AS custom_id, * + FROM (SELECT * FROM '${{inputs.images}}' LIMIT ${{inputs.limit}}); + COPY (SELECT * EXCLUDE ("${{inputs.image_column}}") FROM images) + TO '${{env.WORKFLOW_STORAGE}}/images.parquet' (FORMAT parquet); + COPY ( + SELECT custom_id, + 'POST' AS method, + '/v1/chat/completions' AS url, + {'model': '${{env.WORKFLOW_STORAGE}}/model', + 'messages': [{'role': 'user', 'content': [ + {'type': 'image_url', + 'image_url': {'url': 'data:${{inputs.image_type}};base64,' || base64("${{inputs.image_column}}".bytes)}}, + {'type': 'text', 'text': $$${{inputs.instruction}}$$}]}], + 'max_tokens': 16, + 'temperature': 0, + 'structured_outputs': {'choice': string_split($$${{inputs.labels}}$$, ',')}} AS body + FROM images + ) TO '${{env.WORKFLOW_STORAGE}}/requests.jsonl' (FORMAT json); + SELECT count(*) AS requests FROM images; + + label: + name: Label + uses: swaleio/vllm-batch + compute_type: a100-1 + start_on: + - model + - requests + args: + model: ${{env.WORKFLOW_STORAGE}}/model + input_file: ${{env.WORKFLOW_STORAGE}}/requests.jsonl + output_file: ${{env.WORKFLOW_STORAGE}}/results.jsonl + + collect: + name: Collect labels + uses: swaleio/duckdb + start_on: + - label + args: + sql: | + CREATE TABLE labelled 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); + + compare: + name: Compare when existing labels are given + start_on: + - collect + if: + condition: ${{inputs.gold_column}} + true: agreement + + publish: + name: Upload when asked + start_on: + - compare + if: + condition: ${{inputs.hub_repo}} + true: upload + + agreement: + tasks: + measure: + name: Measure agreement + uses: swaleio/duckdb + args: + sql: | + CREATE TABLE pairs AS + SELECT string_split($$${{inputs.labels}}$$, ',')["${{inputs.gold_column}}" + 1] AS gold, llm_label + FROM '${{env.WORKFLOW_STORAGE}}/labels.parquet'; + SELECT count(*) AS images, + round(avg((gold = llm_label)::INT), 3) AS agreement + FROM pairs; + PIVOT pairs ON llm_label USING count(*) GROUP BY gold ORDER BY gold; + + upload: + tasks: + upload_labels: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + repo_type: dataset + source: ${{env.WORKFLOW_STORAGE}}/labels.parquet + path_in_repo: data/labels.parquet + token: ${{secrets.hf_token}} diff --git a/workflows/compare-finetunes/README.md b/workflows/compare-finetunes/README.md new file mode 100644 index 0000000..bd3a2c3 --- /dev/null +++ b/workflows/compare-finetunes/README.md @@ -0,0 +1,40 @@ +# Compare two fine-tunes + +Trains the same model twice on the same data, with two learning rates, as two +tasks that run at the same time; scores both fine-tunes on one benchmark; and +prints the scores side by side. Swap the learning rates for any other setting +in the config the first task writes. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Write the two training configs | `swaleio/bash` | `cpu-4` | +| Fine-tune A, and B, in parallel | `swaleio/trl-sft` | `a100-1` each | +| Evaluate A, and B, each as soon as its training ends | `swaleio/lm-eval` | `a100-1` each | +| Read both results and compare them | `swaleio/duckdb` | `cpu-4` | + +Every step is its own task. The two branches hold a GPU each while they run. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `model` | `Qwen/Qwen2.5-0.5B-Instruct` | Model to fine-tune. | +| `dataset` | `HuggingFaceH4/ultrafeedback_binarized` | Hub dataset with a `messages` column. | +| `split` | `train_sft[:5000]` | Split, or slice of one, to train on. | +| `learning_rate_a` | `1.0e-5` | Learning rate of fine-tune A. | +| `learning_rate_b` | `5.0e-5` | Learning rate of fine-tune B. | +| `eval_task` | `gsm8k` | The lm-evaluation-harness task both are scored on. | + +Training reads the secret `hf_token`. + +## Output + +The two fine-tuned models in `sft-a/` and `sft-b/` on the workspace, their +scores in `eval-a/` and `eval-b/`, and a table of every metric of `eval_task` +for both in the last task's log. + +## Licenses of the defaults + +- Model: [Qwen/Qwen2.5-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct), Apache-2.0. +- Training data: [HuggingFaceH4/ultrafeedback_binarized](https://huggingface.co/datasets/HuggingFaceH4/ultrafeedback_binarized), MIT. +- Evaluation data: [openai/gsm8k](https://huggingface.co/datasets/openai/gsm8k), MIT. diff --git a/workflows/compare-finetunes/workflow.yaml b/workflows/compare-finetunes/workflow.yaml new file mode 100644 index 0000000..85de1a5 --- /dev/null +++ b/workflows/compare-finetunes/workflow.yaml @@ -0,0 +1,116 @@ +name: Compare two fine-tunes +description: Fine-tunes the same model twice with different learning rates, side by side, evaluates both on the same benchmark, and compares their scores. +compute_type: cpu-4 + +inputs: + model: + description: Hub repo id of the model to fine-tune. + default: Qwen/Qwen2.5-0.5B-Instruct + dataset: + description: Hub dataset with a messages column of chat turns. + default: HuggingFaceH4/ultrafeedback_binarized + split: + description: Split of the dataset to train on. + default: train_sft[:5000] + learning_rate_a: + description: Learning rate of fine-tune A. + default: "1.0e-5" + learning_rate_b: + description: Learning rate of fine-tune B. + default: "5.0e-5" + eval_task: + description: The lm-evaluation-harness task both fine-tunes are scored on. + default: gsm8k + +entry_point: main + +blocks: + main: + tasks: + write_configs: + name: Write training configs + uses: swaleio/bash + args: + script: | + for run in a b; do + if [ "$run" = a ]; then rate=${{inputs.learning_rate_a}}; else rate=${{inputs.learning_rate_b}}; fi + cat > "$WORKFLOW_STORAGE/sft-$run.yaml" < 'sample_len') + ON fine_tune USING first(score) GROUP BY metric ORDER BY metric; diff --git a/workflows/dataset-statistics/README.md b/workflows/dataset-statistics/README.md new file mode 100644 index 0000000..d156b09 --- /dev/null +++ b/workflows/dataset-statistics/README.md @@ -0,0 +1,38 @@ +# Profile, filter and re-pack a dataset + +Looks at a Parquet dataset before it is used, then cleans and re-packs it, all +with DuckDB on a CPU. The first task profiles every column (type, distinct +values, minimum, maximum, average, quartiles, nulls) and the length of the +text column; the second drops exact duplicates of the text and rows outside a +length range, and writes the rest as evenly sized Parquet files. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Profile the columns and the text lengths | `swaleio/duckdb` | `cpu-4` | +| Drop duplicates and outliers, re-pack into Parquet files | `swaleio/duckdb` | `cpu-4` | +| Upload the files, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +Every step is its own task. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `dataset` | the `train_sft` split of `HuggingFaceH4/ultrafeedback_binarized` | Parquet file or glob, as a DuckDB path. | +| `text_column` | `prompt` | Column deduplicated and filtered on. | +| `min_chars` | `20` | Shortest text kept. | +| `max_chars` | `4000` | Longest text kept. | +| `rows_per_file` | `20000` | Rows per output file, roughly. | +| `hub_repo` | empty | Hub dataset repo to upload the files to, under `data/`. | + +The upload reads the secret `hf_token`. For datasets of tens of gigabytes, give +the tasks `cpu-16`. + +## Output + +`packed/train-0.parquet`, `packed/train-1.parquet` and so on, on the +workspace. The profile is in the first task's log. + +## Licenses of the defaults + +- Dataset: [HuggingFaceH4/ultrafeedback_binarized](https://huggingface.co/datasets/HuggingFaceH4/ultrafeedback_binarized), MIT. diff --git a/workflows/dataset-statistics/workflow.yaml b/workflows/dataset-statistics/workflow.yaml new file mode 100644 index 0000000..b2da929 --- /dev/null +++ b/workflows/dataset-statistics/workflow.yaml @@ -0,0 +1,88 @@ +name: Profile filter and re-pack a dataset +description: Profiles a Parquet dataset's columns, drops exact duplicates and rows outside a length range, and re-packs the rest into evenly sized Parquet files. +compute_type: cpu-4 + +inputs: + dataset: + description: Parquet file or glob, as a DuckDB path such as hf://datasets///. + default: hf://datasets/HuggingFaceH4/ultrafeedback_binarized/data/train_sft-*.parquet + text_column: + description: Column whose duplicates are dropped and whose length is filtered on. + default: prompt + min_chars: + description: Shortest text to keep, in characters. + default: "20" + max_chars: + description: Longest text to keep, in characters. + default: "4000" + rows_per_file: + description: Rows in each output Parquet file, roughly. + default: "20000" + hub_repo: + description: Hub dataset repo to upload the files to, as namespace/name. Leave empty to keep them on the workspace only. + default: "" + +entry_point: main + +blocks: + main: + tasks: + profile: + name: Profile + uses: swaleio/duckdb + args: + sql: | + CREATE TABLE source AS SELECT * FROM '${{inputs.dataset}}'; + SUMMARIZE source; + SELECT count(*) AS rows, + count(DISTINCT "${{inputs.text_column}}") AS distinct_texts, + min(length("${{inputs.text_column}}")) AS shortest, + round(median(length("${{inputs.text_column}}"))) AS median_length, + max(length("${{inputs.text_column}}")) AS longest + FROM source; + SELECT (length("${{inputs.text_column}}") // 500) * 500 AS length_from, count(*) AS rows + FROM source GROUP BY ALL ORDER BY length_from LIMIT 20; + + filter_and_pack: + name: Filter and re-pack + uses: swaleio/duckdb + start_on: + - profile + args: + sql: | + CREATE TABLE kept AS + SELECT * EXCLUDE (copy) FROM ( + SELECT *, row_number() OVER (PARTITION BY "${{inputs.text_column}}" ORDER BY "${{inputs.text_column}}") AS copy + FROM '${{inputs.dataset}}' + WHERE length("${{inputs.text_column}}") BETWEEN ${{inputs.min_chars}} AND ${{inputs.max_chars}}) + WHERE copy = 1; + SELECT count(*) AS kept FROM kept; + -- One row group of about rows_per_file rows per file, written single-threaded + -- so the files fill in order. + SET threads = 1; + COPY kept TO '${{env.WORKFLOW_STORAGE}}/packed' + (FORMAT parquet, ROW_GROUP_SIZE ${{inputs.rows_per_file}}, ROW_GROUPS_PER_FILE 1, + FILENAME_PATTERN 'train-{i}', OVERWRITE_OR_IGNORE); + SELECT parse_filename(filename) AS file, count(*) AS rows + FROM read_parquet('${{env.WORKFLOW_STORAGE}}/packed/*.parquet', filename = true) + GROUP BY ALL ORDER BY file; + + publish: + name: Upload when asked + start_on: + - filter_and_pack + if: + condition: ${{inputs.hub_repo}} + true: upload + + upload: + tasks: + upload_files: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + repo_type: dataset + source: ${{env.WORKFLOW_STORAGE}}/packed + path_in_repo: data + token: ${{secrets.hf_token}} diff --git a/workflows/detect-objects/README.md b/workflows/detect-objects/README.md new file mode 100644 index 0000000..1ee622f --- /dev/null +++ b/workflows/detect-objects/README.md @@ -0,0 +1,48 @@ +# Detect objects with a vision-language model + +Finds chosen objects in every image without training a detector. A +vision-language model answers each image with a JSON list of bounding boxes, +which a JSON schema enforces. DuckDB scales the boxes to pixels and compares +how many of each object the model found with how many the dataset annotates, +and a Python step draws the boxes on a few sample images. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Fetch the model | `swaleio/hf-download` | `cpu-4` | +| Write one request per image, with the image inline and the JSON schema of the answer | `swaleio/duckdb` | `cpu-4` | +| Detect | `swaleio/vllm-batch` | `a100-1` | +| Parse the boxes, scale them to pixels, count them per label | `swaleio/duckdb` | `cpu-4` | +| Compare the counts with the annotations | `swaleio/duckdb` | `cpu-4` | +| Draw the boxes on sample images | `swaleio/python-3-13` | `cpu-4` | + +Every step is its own task. An answer that reaches the token limit before its +JSON closes is counted and left out. + +The comparison shows how the model's idea of an object matches the dataset's: +on the default images, the model and the annotations agree on hard hats, while +the annotations mark only some of the people and vests in each picture. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `model` | `Qwen/Qwen3-VL-2B-Instruct` | Vision-language model that answers with boxes as JSON, on a 0 to 1000 grid. | +| `images` | the test split of `keremberke/construction-safety-object-detection` | Parquet file or glob with a Hugging Face Image column, as a DuckDB path. | +| `objects` | `person, hardhat, safety vest` | What to find, separated by commas. | +| `limit` | `200` | Number of images. | +| `samples` | `8` | Number of images to draw the boxes on. | + +The comparison step lists the default dataset's classes; for other images, +edit that step or leave its numbers aside. The download reads the secret +`hf_token`. + +## Output + +`detections.parquet` on the workspace, one row per box with its label and pixel +corners, and the drawn samples in `samples/`. + +## Licenses of the defaults + +- Model: [Qwen/Qwen3-VL-2B-Instruct](https://huggingface.co/Qwen/Qwen3-VL-2B-Instruct), Apache-2.0. +- Dataset: [keremberke/construction-safety-object-detection](https://huggingface.co/datasets/keremberke/construction-safety-object-detection), CC BY 4.0. +- Packages the draw step installs: DuckDB (MIT) and Pillow (MIT-CMU). diff --git a/workflows/detect-objects/workflow.yaml b/workflows/detect-objects/workflow.yaml new file mode 100644 index 0000000..023a04d --- /dev/null +++ b/workflows/detect-objects/workflow.yaml @@ -0,0 +1,157 @@ +name: Detect objects with a vision-language model +description: Asks a vision-language model for the bounding boxes of chosen objects in every image, compares the counts with existing annotations, and draws the boxes on sample images. +compute_type: cpu-4 + +inputs: + model: + description: Hub repo id of a vision-language model that answers with bounding boxes as JSON. + default: Qwen/Qwen3-VL-2B-Instruct + images: + description: Parquet file or glob with a Hugging Face Image column, as a DuckDB path. + default: hf://datasets/keremberke/construction-safety-object-detection@~parquet/full/test/*.parquet + objects: + description: What to find, as the model should read it. + default: person, hardhat, safety vest + limit: + description: Number of images. + default: "200" + samples: + description: Number of images to draw the boxes on. + default: "8" + +entry_point: main + +blocks: + main: + tasks: + fetch_model: + name: Fetch model + uses: swaleio/hf-download + args: + repo: ${{inputs.model}} + dest: ${{env.WORKFLOW_STORAGE}}/model + token: ${{secrets.hf_token}} + + requests: + name: Write detection requests + uses: swaleio/duckdb + args: + sql: | + CREATE TABLE images AS + SELECT 'img-' || lpad((row_number() OVER () - 1)::VARCHAR, 5, '0') AS custom_id, * + FROM (SELECT * FROM '${{inputs.images}}' LIMIT ${{inputs.limit}}); + COPY images TO '${{env.WORKFLOW_STORAGE}}/images.parquet' (FORMAT parquet); + COPY ( + SELECT custom_id, 'POST' AS method, '/v1/chat/completions' AS url, + {'model': '${{env.WORKFLOW_STORAGE}}/model', + 'messages': [{'role': 'user', 'content': [ + {'type': 'image_url', 'image_url': {'url': 'data:image/jpeg;base64,' || base64(image.bytes)}}, + {'type': 'text', 'text': $$Locate every $$ || $$${{inputs.objects}}$$ || $$ in the image. Answer with a JSON list of objects, each with "bbox_2d" as [x1, y1, x2, y2] and "label".$$}]}], + 'max_tokens': 1024, 'temperature': 0, + 'structured_outputs': {'json': { + 'type': 'array', 'maxItems': 50, + 'items': {'type': 'object', + 'properties': {'bbox_2d': {'type': 'array', 'items': {'type': 'number'}, 'minItems': 4, 'maxItems': 4}, + 'label': {'type': 'string'}}, + 'required': ['bbox_2d', 'label']}}}} AS body + FROM images + ) TO '${{env.WORKFLOW_STORAGE}}/requests.jsonl' (FORMAT json); + SELECT count(*) AS images FROM images; + + detect: + name: Detect + uses: swaleio/vllm-batch + compute_type: a100-1 + start_on: + - fetch_model + - requests + args: + model: ${{env.WORKFLOW_STORAGE}}/model + input_file: ${{env.WORKFLOW_STORAGE}}/requests.jsonl + output_file: ${{env.WORKFLOW_STORAGE}}/results.jsonl + + collect: + name: Collect boxes + uses: swaleio/duckdb + start_on: + - detect + args: + sql: | + -- An answer cut off at max_tokens is not valid JSON and is left out. + CREATE TABLE answers AS + SELECT custom_id, response.body.choices[1].message.content AS content + FROM read_json('${{env.WORKFLOW_STORAGE}}/results.jsonl'); + SELECT count(*) FILTER (json_valid(content)) AS answered, + count(*) FILTER (NOT json_valid(content)) AS cut_off + FROM answers; + -- The model gives coordinates from 0 to 1000 across the image; scale them to pixels. + CREATE TABLE detections AS + WITH answers AS ( + SELECT custom_id, content::JSON AS boxes FROM answers WHERE json_valid(content)) + SELECT a.custom_id, i.image_id, lower(trim(b.label)) AS label, + b.bbox_2d[1] * i.width / 1000 AS x1, b.bbox_2d[2] * i.height / 1000 AS y1, + b.bbox_2d[3] * i.width / 1000 AS x2, b.bbox_2d[4] * i.height / 1000 AS y2 + FROM answers a + JOIN '${{env.WORKFLOW_STORAGE}}/images.parquet' i USING (custom_id), + unnest(from_json(a.boxes, '[{"bbox_2d": ["DOUBLE"], "label": "VARCHAR"}]')) AS t(b); + COPY detections TO '${{env.WORKFLOW_STORAGE}}/detections.parquet' (FORMAT parquet); + SELECT label, count(*) AS boxes, count(DISTINCT custom_id) AS images + FROM detections GROUP BY label ORDER BY boxes DESC; + + compare: + name: Compare counts with annotations + uses: swaleio/duckdb + start_on: + - collect + args: + sql: | + -- The annotation classes of the default dataset, in their label order. + CREATE TABLE classes AS + SELECT unnest(['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']) AS label, + generate_subscripts(['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'], 1) - 1 AS category; + CREATE TABLE annotated AS + SELECT i.custom_id, c.label + FROM '${{env.WORKFLOW_STORAGE}}/images.parquet' i, + unnest(i.objects.category) AS t(category) + JOIN classes c USING (category); + SELECT label, + (SELECT count(*) FROM annotated a WHERE a.label = l.label) AS annotated, + (SELECT count(*) FROM '${{env.WORKFLOW_STORAGE}}/detections.parquet' d WHERE d.label = l.label) AS detected + FROM (SELECT trim(unnest(string_split($$${{inputs.objects}}$$, ','))) AS label) l; + + draw: + name: Draw sample boxes + uses: swaleio/python-3-13 + start_on: + - collect + args: + script: | + import io, os, subprocess, sys + subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "--target", "/tmp/deps", + "duckdb==2.0.1", "pillow==13.0.0"], check=True) + sys.path.insert(0, "/tmp/deps") + import duckdb + from PIL import Image, ImageDraw + + storage = os.environ["WORKFLOW_STORAGE"] + out = os.path.join(storage, "samples") + os.makedirs(out, exist_ok=True) + con = duckdb.connect() + images = con.execute( + f"SELECT custom_id, image.bytes FROM '{storage}/images.parquet' ORDER BY custom_id LIMIT ${{inputs.samples}}" + ).fetchall() + for custom_id, data in images: + img = Image.open(io.BytesIO(data)).convert("RGB") + draw = ImageDraw.Draw(img) + boxes = con.execute( + f"SELECT label, x1, y1, x2, y2 FROM '{storage}/detections.parquet' WHERE custom_id = ?", [custom_id] + ).fetchall() + for label, x1, y1, x2, y2 in boxes: + draw.rectangle([x1, y1, x2, y2], outline="red", width=3) + draw.text((x1 + 4, y1 + 4), label, fill="red") + img.save(os.path.join(out, f"{custom_id}.jpg")) + print(custom_id, len(boxes), "boxes") diff --git a/workflows/distill-model/README.md b/workflows/distill-model/README.md new file mode 100644 index 0000000..40fdfda --- /dev/null +++ b/workflows/distill-model/README.md @@ -0,0 +1,39 @@ +# 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 +word-by-word distribution over the answer; the student is scored on GSM8K's +test split before and after. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Turn GSM8K questions into chat prompts | `swaleio/duckdb` | `cpu-4` | +| Write the training config | `swaleio/bash` | `cpu-4` | +| Distill | `swaleio/trl-distillation` | `a100-1` | +| Evaluate the student before, and after | `swaleio/lm-eval` | `a100-1` each | +| Compare the two scores | `swaleio/duckdb` | `cpu-4` | +| Upload the distilled student, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +Every step is its own task. The student's first score is taken while it +trains. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `student` | `Qwen/Qwen2.5-0.5B-Instruct` | Student model; all of its weights are trained. | +| `teacher` | `Qwen/Qwen2.5-1.5B-Instruct` | Teacher model; it must share the student's vocabulary. | +| `train_prompts` | `4000` | GSM8K training questions to distill on. | +| `hub_repo` | empty | Hub model repo to upload the student to. | + +Training, the first evaluation and the upload read the secret `hf_token`. + +## Output + +The distilled student in `student/` on the workspace, the scores in +`eval-before/` and `eval-after/`, and the comparison in the last task's log. + +## Licenses of the defaults + +- Models: [Qwen/Qwen2.5-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct) and [Qwen/Qwen2.5-1.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct), Apache-2.0. +- Dataset: [openai/gsm8k](https://huggingface.co/datasets/openai/gsm8k), MIT. diff --git a/workflows/distill-model/workflow.yaml b/workflows/distill-model/workflow.yaml new file mode 100644 index 0000000..5e3f0b1 --- /dev/null +++ b/workflows/distill-model/workflow.yaml @@ -0,0 +1,122 @@ +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. +compute_type: cpu-4 + +inputs: + student: + description: Hub repo id of the student model. All of its weights are trained. + default: Qwen/Qwen2.5-0.5B-Instruct + teacher: + description: Hub repo id of the teacher model; it must share the student's vocabulary. + default: Qwen/Qwen2.5-1.5B-Instruct + train_prompts: + description: Number of GSM8K training questions to distill on. + default: "4000" + hub_repo: + description: Hub model repo to upload the distilled student to, as namespace/name. Leave empty to keep it on the workspace only. + default: "" + +entry_point: main + +blocks: + main: + tasks: + prepare: + name: Prepare prompts + uses: swaleio/duckdb + args: + sql: | + COPY ( + SELECT [{'role': 'user', 'content': question || '\nSolve it step by step.'}] AS prompt + FROM 'hf://datasets/openai/gsm8k/main/train-*.parquet' + LIMIT ${{inputs.train_prompts}} + ) TO '${{env.WORKFLOW_STORAGE}}/distill-prompts.parquet' (FORMAT parquet); + + write_config: + name: Write training config + uses: swaleio/bash + args: + script: | + cat > "$WORKFLOW_STORAGE/distillation.yaml" <>'$."exact_match,strict-match"')::DOUBLE, 4) AS strict_match, + round((results.gsm8k->>'$."exact_match,flexible-extract"')::DOUBLE, 4) AS flexible_extract + FROM read_json(['${{env.WORKFLOW_STORAGE}}/eval-before/*/results_*.json', + '${{env.WORKFLOW_STORAGE}}/eval-after/*/results_*.json'], + filename = true, columns = {'results': 'STRUCT(gsm8k JSON)'}) + ORDER BY student DESC; + + publish: + name: Upload when asked + start_on: + - compare + if: + condition: ${{inputs.hub_repo}} + true: upload + + upload: + tasks: + upload_model: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + source: ${{env.WORKFLOW_STORAGE}}/student + token: ${{secrets.hf_token}} diff --git a/workflows/dpo-alignment/README.md b/workflows/dpo-alignment/README.md new file mode 100644 index 0000000..e660588 --- /dev/null +++ b/workflows/dpo-alignment/README.md @@ -0,0 +1,48 @@ +# Align a model with DPO + +Aligns a chat model to human preferences with direct preference optimization, +then checks that it helped. The base model and the aligned model both answer +the same held-out prompts, a judge model compares each pair of answers without +knowing which model wrote which, and the last step reports how often the +aligned model wins. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Write the training config | `swaleio/bash` | `cpu-4` | +| Fetch the base model, and the judge | `swaleio/hf-download` | `cpu-4` | +| Align the model | `swaleio/trl-dpo` | `a100-1` | +| Write the held-out requests | `swaleio/duckdb` | `cpu-4` | +| Answer with the base model, and with the aligned model | `swaleio/vllm-batch` | `a100-1` each | +| Pair the answers, alternating their order, and write the judge requests | `swaleio/duckdb` | `cpu-4` | +| Judge each pair | `swaleio/vllm-batch` | `a100-1` | +| Count wins, losses and ties | `swaleio/duckdb` | `cpu-4` | +| Upload the aligned model, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +Every step is its own task. The base model answers while the aligned one is +still training. + +The whole model is trained, not a LoRA adapter, so vLLM can serve the result as +it is. A 0.5B model trains on one A100 this way; for larger models, add +`use_peft: true` to the config and merge the adapter before answering. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `model` | `Qwen/Qwen2.5-0.5B-Instruct` | Chat model to align. | +| `judge` | `Qwen/Qwen3-8B` | Judge model. | +| `train_split` | `train_prefs[:10000]` | Pairs of `HuggingFaceH4/ultrafeedback_binarized` to train on. | +| `eval_prompts` | `200` | Held-out prompts, from its `test_prefs` split. | +| `hub_repo` | empty | Hub model repo to upload the aligned model to. | + +The downloads, the training and the upload read the secret `hf_token`. + +## Output + +The aligned model in `aligned/` on the workspace, each judged pair in +`verdicts.parquet`, and the win rate in the last task's log. + +## Licenses of the defaults + +- Models: [Qwen/Qwen2.5-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct) and [Qwen/Qwen3-8B](https://huggingface.co/Qwen/Qwen3-8B), Apache-2.0. +- Dataset: [HuggingFaceH4/ultrafeedback_binarized](https://huggingface.co/datasets/HuggingFaceH4/ultrafeedback_binarized), MIT. diff --git a/workflows/dpo-alignment/workflow.yaml b/workflows/dpo-alignment/workflow.yaml new file mode 100644 index 0000000..76ae940 --- /dev/null +++ b/workflows/dpo-alignment/workflow.yaml @@ -0,0 +1,199 @@ +name: Align a model with DPO +description: Aligns a chat model to preference pairs with TRL's DPO, then has a judge model compare its answers with the base model's on held-out prompts and reports the win rate. +compute_type: cpu-4 + +inputs: + model: + description: Hub repo id of the chat model to align. All of its weights are trained. + default: Qwen/Qwen2.5-0.5B-Instruct + judge: + description: Hub repo id of the judge model. + default: Qwen/Qwen3-8B + train_split: + description: Preference pairs to train on, from HuggingFaceH4/ultrafeedback_binarized. + default: train_prefs[:10000] + eval_prompts: + description: Number of held-out prompts the two models answer for the judge. + default: "200" + hub_repo: + description: Hub model repo to upload the aligned model to, as namespace/name. Leave empty to keep it on the workspace only. + default: "" + +entry_point: main + +blocks: + main: + tasks: + write_config: + name: Write training config + uses: swaleio/bash + args: + script: | + cat > "$WORKFLOW_STORAGE/dpo.yaml" < max_tokens: + continue + yield start[s] + end[e], offsets[s][0], offsets[e][1] + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--scores", required=True, help="JSON Lines file of window scores from predict.py") + p.add_argument("--examples", required=True, help="JSON Lines file of the eval questions with id and context") + p.add_argument("--output", required=True, help="JSON Lines file the answers are written to") + p.add_argument("--n-best", type=int, default=20) + p.add_argument("--max-answer-tokens", type=int, default=60) + args = p.parse_args() + + best = defaultdict(lambda: (float("-inf"), 0, 0)) + with open(args.scores) as f: + for line in f: + window = json.loads(line) + for candidate in best_spans(window["start"], window["end"], window["offsets"], + args.n_best, args.max_answer_tokens): + if candidate[0] > best[window["example_id"]][0]: + best[window["example_id"]] = candidate + count = 0 + with open(args.examples) as f, open(args.output, "w") as out: + for line in f: + example = json.loads(line) + _, start, end = best[example["id"]] + out.write(json.dumps({"id": example["id"], "prediction": example["context"][start:end], + "answers": example["answers"]}) + "\n") + count += 1 + print(f"answered {count} questions") + + +if __name__ == "__main__": + main() diff --git a/workflows/extractive-qa/predict.py b/workflows/extractive-qa/predict.py new file mode 100644 index 0000000..0384ebe --- /dev/null +++ b/workflows/extractive-qa/predict.py @@ -0,0 +1,42 @@ +"""Scores every token of every eval window as an answer start and end, on a GPU. + +Writes one JSON line per window with its example id, its token offsets and the +start and end scores; picking the answers from them needs no GPU. +""" + +import argparse +import json + +import torch +from datasets import load_from_disk +from transformers import AutoModelForQuestionAnswering + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Directory of the fine-tuned model") + p.add_argument("--data", required=True, help="Directory of the tokenized eval windows") + p.add_argument("--output", required=True, help="JSON Lines file the scores are written to") + p.add_argument("--batch-size", type=int, default=64) + args = p.parse_args() + + model = AutoModelForQuestionAnswering.from_pretrained(args.model).cuda().eval() + windows = load_from_disk(args.data) + inputs = [c for c in ("input_ids", "attention_mask", "token_type_ids") if c in windows.column_names] + with open(args.output, "w") as out, torch.no_grad(): + for start in range(0, len(windows), args.batch_size): + batch = windows[start:start + args.batch_size] + tensors = {c: torch.tensor(batch[c]).cuda() for c in inputs} + result = model(**tensors) + for i in range(len(batch["example_id"])): + out.write(json.dumps({ + "example_id": batch["example_id"][i], + "offsets": batch["offset_mapping"][i], + "start": [round(x, 4) for x in result.start_logits[i].float().tolist()], + "end": [round(x, 4) for x in result.end_logits[i].float().tolist()], + }) + "\n") + print(f"scored {len(windows)} windows") + + +if __name__ == "__main__": + main() diff --git a/workflows/extractive-qa/preprocess.py b/workflows/extractive-qa/preprocess.py new file mode 100644 index 0000000..2c8d8ec --- /dev/null +++ b/workflows/extractive-qa/preprocess.py @@ -0,0 +1,77 @@ +"""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, +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. +""" + +import argparse + +from datasets import load_dataset +from transformers import AutoTokenizer + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Hub repo id or directory whose tokenizer to use") + p.add_argument("--train", required=True, help="Parquet file with id, question, context and answers columns") + p.add_argument("--eval", required=True, help="Parquet file with id, question, context and answers columns") + p.add_argument("--max-length", type=int, default=384) + p.add_argument("--stride", type=int, default=128) + p.add_argument("--output", required=True, help="Directory the train and eval windows are saved under") + args = p.parse_args() + + tokenizer = AutoTokenizer.from_pretrained(args.model) + splits = load_dataset("parquet", data_files={"train": args.train, "eval": args.eval}) + + def windows(batch): + return tokenizer( + [q.strip() for q in batch["question"]], batch["context"], + truncation="only_second", max_length=args.max_length, stride=args.stride, + return_overflowing_tokens=True, return_offsets_mapping=True, padding="max_length", + ) + + def train_windows(batch): + encoded = windows(batch) + starts, ends = [], [] + for i, offsets in enumerate(encoded["offset_mapping"]): + example = encoded["overflow_to_sample_mapping"][i] + answers = batch["answers"][example] + sequence = encoded.sequence_ids(i) + context = [t for t, s in enumerate(sequence) if s == 1] + start_char = answers["answer_start"][0] + end_char = start_char + len(answers["text"][0]) + if offsets[context[0]][0] > start_char or offsets[context[-1]][1] < end_char: + starts.append(0) + ends.append(0) + continue + starts.append(next(t for t in context if offsets[t][1] > start_char)) + ends.append(next(t for t in reversed(context) if offsets[t][0] < end_char)) + encoded["start_positions"] = starts + encoded["end_positions"] = ends + encoded.pop("offset_mapping") + encoded.pop("overflow_to_sample_mapping") + return encoded + + def eval_windows(batch): + encoded = windows(batch) + encoded["example_id"] = [batch["id"][e] for e in encoded.pop("overflow_to_sample_mapping")] + encoded["offset_mapping"] = [ + [o if s == 1 else None for o, s in zip(offsets, encoded.sequence_ids(i))] + for i, offsets in enumerate(encoded["offset_mapping"]) + ] + return encoded + + columns = splits["train"].column_names + train = splits["train"].map(train_windows, batched=True, remove_columns=columns) + evaluation = splits["eval"].map(eval_windows, batched=True, remove_columns=columns) + train.save_to_disk(f"{args.output}/train") + evaluation.save_to_disk(f"{args.output}/eval") + print(f"train: {len(splits['train'])} questions in {len(train)} windows") + print(f"eval: {len(splits['eval'])} questions in {len(evaluation)} windows") + + +if __name__ == "__main__": + main() diff --git a/workflows/extractive-qa/score.py b/workflows/extractive-qa/score.py new file mode 100644 index 0000000..af11eb9 --- /dev/null +++ b/workflows/extractive-qa/score.py @@ -0,0 +1,53 @@ +"""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 +extra spaces. A question with several reference answers takes the best score +over them. +""" + +import argparse +import json +import re +import string +from collections import Counter + + +def normalise(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() + common = sum((Counter(predicted) & Counter(gold)).values()) + if not predicted or not gold: + return float(predicted == gold) + if common == 0: + return 0.0 + precision, recall = common / len(predicted), common / len(gold) + return 2 * precision * recall / (precision + recall) + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--answers", required=True, help="JSON Lines file with prediction and answers per question") + p.add_argument("--output", required=True, help="JSON file the scores are written to") + args = p.parse_args() + + exact, overlap, count = 0.0, 0.0, 0 + with open(args.answers) as f: + for line in f: + row = json.loads(line) + references = row["answers"]["text"] + exact += max(float(normalise(row["prediction"]) == normalise(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)} + with open(args.output, "w") as f: + json.dump(scores, f, indent=2) + print(json.dumps(scores)) + + +if __name__ == "__main__": + main() diff --git a/workflows/extractive-qa/train.py b/workflows/extractive-qa/train.py new file mode 100644 index 0000000..c9c9370 --- /dev/null +++ b/workflows/extractive-qa/train.py @@ -0,0 +1,45 @@ +"""Fine-tunes an extractive question-answering model on labelled 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. +""" + +import argparse + +from datasets import load_from_disk +from transformers import AutoModelForQuestionAnswering, AutoTokenizer, Trainer, TrainingArguments + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Hub repo id or directory of the model to fine-tune") + p.add_argument("--data", required=True, help="Directory holding the tokenized train windows") + p.add_argument("--output", required=True, help="Directory the fine-tuned model is saved to") + p.add_argument("--epochs", type=float, default=2) + p.add_argument("--learning-rate", type=float, default=3e-5) + p.add_argument("--batch-size", type=int, default=16) + args = p.parse_args() + + tokenizer = AutoTokenizer.from_pretrained(args.model) + model = AutoModelForQuestionAnswering.from_pretrained(args.model) + trainer = Trainer( + model=model, + args=TrainingArguments( + output_dir=f"{args.output}-checkpoints", + num_train_epochs=args.epochs, + learning_rate=args.learning_rate, + per_device_train_batch_size=args.batch_size, + save_strategy="no", + bf16=True, + dataloader_num_workers=2, + report_to="none", + ), + train_dataset=load_from_disk(f"{args.data}/train"), + ) + trainer.train() + trainer.save_model(args.output) + tokenizer.save_pretrained(args.output) + + +if __name__ == "__main__": + main() diff --git a/workflows/extractive-qa/workflow.yaml b/workflows/extractive-qa/workflow.yaml new file mode 100644 index 0000000..7b74073 --- /dev/null +++ b/workflows/extractive-qa/workflow.yaml @@ -0,0 +1,161 @@ +name: Extractive question answering +description: Fine-tunes a question-answering model to find answers inside long documents, with windowing on a CPU, training and scoring tokens on a GPU, and answer picking and exact match and F1 on a CPU. +compute_type: cpu-4 + +inputs: + model: + description: Hub repo id of the question-answering model to fine-tune. + default: distilbert/distilbert-base-cased-distilled-squad + data: + description: Parquet file or glob of questions in SQuAD form (id, question, context, answers), as a DuckDB path. + default: hf://datasets/deepset/covid_qa_deepset@~parquet/covid_qa_deepset/train/*.parquet + eval_every: + description: One document in this many is held out for evaluation, with all its questions. + default: "10" + epochs: + description: Training epochs. + default: "2" + examples_ref: + description: Branch, tag or full commit SHA of swaleio/examples whose scripts run. + default: main + hub_repo: + description: Hub 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: | + -- Questions about one document stay in the same split, so evaluation reads + -- documents the model never saw. + CREATE TABLE questions AS + SELECT id::VARCHAR AS id, question, context, answers, document_id + FROM '${{inputs.data}}' WHERE len(answers.text) > 0; + COPY (SELECT * EXCLUDE (document_id) FROM questions WHERE document_id % ${{inputs.eval_every}} <> 0) + TO '${{env.WORKFLOW_STORAGE}}/train.parquet' (FORMAT parquet); + COPY (SELECT * EXCLUDE (document_id) FROM questions WHERE document_id % ${{inputs.eval_every}} = 0) + TO '${{env.WORKFLOW_STORAGE}}/eval.parquet' (FORMAT parquet); + COPY (SELECT id, context, answers FROM questions WHERE document_id % ${{inputs.eval_every}} = 0) + TO '${{env.WORKFLOW_STORAGE}}/eval-examples.jsonl' (FORMAT json); + SELECT document_id % ${{inputs.eval_every}} = 0 AS held_out, count(DISTINCT document_id) AS documents, + count(*) AS questions, round(avg(length(context))) AS mean_context_characters + FROM questions GROUP BY ALL ORDER BY held_out; + + tokenize: + name: Split contexts into windows + 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-tokenize.txt"], check=True) + subprocess.run([sys.executable, f"{examples}/workflows/extractive-qa/preprocess.py", + "--model", f"{storage}/base-model", + "--train", f"{storage}/train.parquet", "--eval", f"{storage}/eval.parquet", + "--output", f"{storage}/tokenized"], + env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True) + + train: + name: Train + uses: swaleio/transformers + compute_type: a100-1 + start_on: + - tokenize + args: + script: | + import os, subprocess, sys + + storage = os.environ["WORKFLOW_STORAGE"] + subprocess.run([sys.executable, f"{storage}/examples/workflows/extractive-qa/train.py", + "--model", f"{storage}/base-model", "--data", f"{storage}/tokenized", + "--epochs", "${{inputs.epochs}}", "--output", f"{storage}/model"], check=True) + + predict: + name: Score answer tokens + 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/extractive-qa/predict.py", + "--model", f"{storage}/model", "--data", f"{storage}/tokenized/eval", + "--output", f"{storage}/window-scores.jsonl"], check=True) + + postprocess: + name: Pick the answers + uses: swaleio/python-3-13 + start_on: + - predict + args: + script: | + import os, subprocess, sys + + storage = os.environ["WORKFLOW_STORAGE"] + subprocess.run([sys.executable, f"{storage}/examples/workflows/extractive-qa/postprocess.py", + "--scores", f"{storage}/window-scores.jsonl", + "--examples", f"{storage}/eval-examples.jsonl", + "--output", f"{storage}/answers.jsonl"], check=True) + + score: + name: Score + uses: swaleio/python-3-13 + start_on: + - postprocess + args: + script: | + import os, subprocess, sys + + storage = os.environ["WORKFLOW_STORAGE"] + subprocess.run([sys.executable, f"{storage}/examples/workflows/extractive-qa/score.py", + "--answers", f"{storage}/answers.jsonl", "--output", f"{storage}/metrics.json"], check=True) + + publish: + name: Upload when asked + start_on: + - score + if: + condition: ${{inputs.hub_repo}} + true: upload + + upload: + tasks: + upload_model: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + source: ${{env.WORKFLOW_STORAGE}}/model + token: ${{secrets.hf_token}} diff --git a/workflows/finetune-evaluate-quantize/README.md b/workflows/finetune-evaluate-quantize/README.md new file mode 100644 index 0000000..2c0b6cd --- /dev/null +++ b/workflows/finetune-evaluate-quantize/README.md @@ -0,0 +1,45 @@ +# Fine-tune, evaluate, quantize and publish + +The whole path from a base model to a quantized file that runs on a laptop: +supervised fine-tuning with TRL, a benchmark score with lm-evaluation-harness, +conversion to GGUF, 4-bit quantization with llama.cpp, and an upload to the +Hub. Evaluation and conversion run side by side once training is done. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Write the training config | `swaleio/bash` | `cpu-4` | +| Fine-tune the whole model | `swaleio/trl-sft` | `a100-1` | +| Make the tokenizer config readable by the converter | `swaleio/python-3-13` | `cpu-4` | +| Evaluate | `swaleio/lm-eval` | `a100-1` | +| Convert to a 16-bit GGUF file | `swaleio/llamacpp-convert` | `cpu-4` | +| Quantize | `swaleio/llamacpp-quantize` | `cpu-4` | +| Upload the quantized file, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +Every step is its own task. The tokenizer step exists because Transformers 5, +which trains the model, saves `extra_special_tokens` in a form the converter's +Transformers 4 cannot read; the step removes that key, whose tokens are also +in `tokenizer.json`. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `model` | `Qwen/Qwen2.5-0.5B-Instruct` | Model to fine-tune. All of its weights are trained. | +| `dataset` | `HuggingFaceH4/ultrafeedback_binarized` | Hub dataset with a `messages` column. | +| `split` | `train_sft[:5000]` | Split, or slice of one, to train on. | +| `eval_tasks` | `gsm8k` | lm-evaluation-harness tasks, separated by commas. | +| `preset` | `Q4_K_M` | llama.cpp quantization preset. | +| `hub_repo` | empty | Hub model repo to upload the quantized file to. | + +Training and the upload read the secret `hf_token`. + +## Output + +On the workspace: the fine-tuned model in `sft/`, the scores in `eval/`, and +`release/model-.gguf`. + +## Licenses of the defaults + +- Model: [Qwen/Qwen2.5-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct), Apache-2.0. The fine-tuned model keeps it. +- Training data: [HuggingFaceH4/ultrafeedback_binarized](https://huggingface.co/datasets/HuggingFaceH4/ultrafeedback_binarized), MIT. +- Evaluation data, which lm-evaluation-harness downloads: [openai/gsm8k](https://huggingface.co/datasets/openai/gsm8k), MIT. Other tasks bring their own datasets and licenses. diff --git a/workflows/finetune-evaluate-quantize/workflow.yaml b/workflows/finetune-evaluate-quantize/workflow.yaml new file mode 100644 index 0000000..130d3e9 --- /dev/null +++ b/workflows/finetune-evaluate-quantize/workflow.yaml @@ -0,0 +1,130 @@ +name: Fine-tune evaluate quantize and publish +description: Fine-tunes a small chat model with TRL, evaluates it with lm-evaluation-harness, converts it to GGUF, quantizes it, and uploads the quantized file to the Hub. +compute_type: cpu-4 + +inputs: + model: + description: Hub repo id of the model to fine-tune. The whole model is trained, so keep it small or raise the compute type. + default: Qwen/Qwen2.5-0.5B-Instruct + dataset: + description: Hub dataset with a messages column of chat turns. + default: HuggingFaceH4/ultrafeedback_binarized + split: + description: Split of the dataset to train on; a slice such as train_sft[:5000] trains on part of it. + default: train_sft[:5000] + eval_tasks: + description: lm-evaluation-harness tasks to score the fine-tuned model on, separated by commas. + default: gsm8k + preset: + description: llama.cpp quantization preset. + default: Q4_K_M + hub_repo: + description: Hub model repo to upload the quantized GGUF file to, as namespace/name. Leave empty to keep it on the workspace only. + default: "" + +entry_point: main + +blocks: + main: + tasks: + write_config: + name: Write training config + uses: swaleio/bash + args: + script: | + mkdir -p "$WORKFLOW_STORAGE/gguf" "$WORKFLOW_STORAGE/release" + cat > "$WORKFLOW_STORAGE/sft.yaml" <//. + default: hf://datasets/openai/gsm8k/main/test-*.parquet + prompt_column: + description: Column of the prompts file that holds each prompt. + default: question + limit: + description: Number of prompts to answer. + default: "200" + max_tokens: + description: Longest answer, in tokens. + default: "512" + hub_repo: + description: Hub dataset repo to upload the answers to, as namespace/name. Leave empty to keep them on the workspace only. + default: "" + +entry_point: main + +blocks: + main: + tasks: + model: + name: Fetch model + uses: swaleio/hf-download + args: + repo: ${{inputs.model}} + dest: ${{env.WORKFLOW_STORAGE}}/model + token: ${{secrets.hf_token}} + + requests: + name: Write requests + uses: swaleio/duckdb + args: + sql: | + CREATE TABLE prompts AS + SELECT 'row-' || lpad((row_number() OVER () - 1)::VARCHAR, 6, '0') AS custom_id, * + FROM (SELECT * FROM '${{inputs.prompts}}' LIMIT ${{inputs.limit}}); + COPY prompts TO '${{env.WORKFLOW_STORAGE}}/prompts.parquet' (FORMAT parquet); + COPY ( + SELECT custom_id, + 'POST' AS method, + '/v1/chat/completions' AS url, + {'model': '${{env.WORKFLOW_STORAGE}}/model', + 'messages': [{'role': 'user', 'content': "${{inputs.prompt_column}}"}], + 'max_tokens': ${{inputs.max_tokens}}} AS body + FROM prompts + ) TO '${{env.WORKFLOW_STORAGE}}/requests.jsonl' (FORMAT json); + SELECT count(*) AS requests FROM prompts; + + generate: + name: Generate + uses: swaleio/vllm-batch + compute_type: a100-1 + start_on: + - model + - requests + args: + model: ${{env.WORKFLOW_STORAGE}}/model + input_file: ${{env.WORKFLOW_STORAGE}}/requests.jsonl + output_file: ${{env.WORKFLOW_STORAGE}}/results.jsonl + + collect: + name: Collect answers + uses: swaleio/duckdb + start_on: + - generate + args: + sql: | + CREATE TABLE answers AS + SELECT p.*, + r.response.body.choices[1].message.content AS response, + r.response.body.choices[1].finish_reason AS finish_reason + FROM '${{env.WORKFLOW_STORAGE}}/prompts.parquet' p + JOIN read_json('${{env.WORKFLOW_STORAGE}}/results.jsonl') r USING (custom_id) + ORDER BY custom_id; + SELECT finish_reason, count(*) AS answers FROM answers GROUP BY ALL; + COPY answers TO '${{env.WORKFLOW_STORAGE}}/responses.parquet' (FORMAT parquet); + + publish: + name: Upload when asked + start_on: + - collect + if: + condition: ${{inputs.hub_repo}} + true: upload + + upload: + tasks: + upload_answers: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + repo_type: dataset + source: ${{env.WORKFLOW_STORAGE}}/responses.parquet + path_in_repo: data/responses.parquet + token: ${{secrets.hf_token}} diff --git a/workflows/grpo-math/README.md b/workflows/grpo-math/README.md new file mode 100644 index 0000000..0c8192f --- /dev/null +++ b/workflows/grpo-math/README.md @@ -0,0 +1,40 @@ +# Train maths reasoning with GRPO + +Trains a model to solve maths 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 +base model and the trained model are both scored on GSM8K's test split. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Turn GSM8K questions into chat prompts and reference solutions | `swaleio/duckdb` | `cpu-4` | +| Write the training config | `swaleio/bash` | `cpu-4` | +| Train | `swaleio/trl-grpo` | `a100-1` | +| Evaluate the base model, and the trained model | `swaleio/lm-eval` | `a100-1` each | +| Compare the two scores | `swaleio/duckdb` | `cpu-4` | +| Upload the trained model, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +Every step is its own task. The base model is scored while the other model +trains. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `model` | `Qwen/Qwen2.5-0.5B-Instruct` | Chat model to train; all of its weights are trained. | +| `train_questions` | `2000` | GSM8K training questions to train on. | +| `hub_repo` | empty | Hub model repo to upload the trained model to. | + +Training, the base model's evaluation and the upload read the secret +`hf_token`. + +## Output + +The trained model in `trained/` on the workspace, the scores in `eval-base/` +and `eval-trained/`, and the comparison in the last task's log. + +## Licenses of the defaults + +- Model: [Qwen/Qwen2.5-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct), Apache-2.0. +- Dataset: [openai/gsm8k](https://huggingface.co/datasets/openai/gsm8k), MIT. diff --git a/workflows/grpo-math/workflow.yaml b/workflows/grpo-math/workflow.yaml new file mode 100644 index 0000000..4d4a32f --- /dev/null +++ b/workflows/grpo-math/workflow.yaml @@ -0,0 +1,124 @@ +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. +compute_type: cpu-4 + +inputs: + model: + description: Hub repo id of the chat model to train. All of its weights are trained. + default: Qwen/Qwen2.5-0.5B-Instruct + train_questions: + description: Number of GSM8K training questions to train on. + default: "2000" + hub_repo: + description: Hub model repo to upload the trained model to, as namespace/name. Leave empty to keep it on the workspace only. + default: "" + +entry_point: main + +blocks: + main: + tasks: + prepare: + name: Prepare prompts and solutions + uses: swaleio/duckdb + args: + sql: | + -- GRPO reads a prompt column of chat messages; accuracy_reward compares each + -- answer with the solution column, the number after #### in GSM8K's answers. + COPY ( + SELECT [{'role': 'user', 'content': question || '\nPut the final answer in \boxed{}.'}] AS prompt, + trim(split_part(answer, '####', 2)) AS solution + FROM 'hf://datasets/openai/gsm8k/main/train-*.parquet' + LIMIT ${{inputs.train_questions}} + ) TO '${{env.WORKFLOW_STORAGE}}/grpo-train.parquet' (FORMAT parquet); + SELECT count(*) AS questions FROM '${{env.WORKFLOW_STORAGE}}/grpo-train.parquet'; + + write_config: + name: Write training config + uses: swaleio/bash + args: + script: | + cat > "$WORKFLOW_STORAGE/grpo.yaml" <>'$."exact_match,strict-match"')::DOUBLE, 4) AS strict_match, + round((results.gsm8k->>'$."exact_match,flexible-extract"')::DOUBLE, 4) AS flexible_extract + FROM read_json(['${{env.WORKFLOW_STORAGE}}/eval-base/*/results_*.json', + '${{env.WORKFLOW_STORAGE}}/eval-trained/*/results_*.json'], + filename = true, columns = {'results': 'STRUCT(gsm8k JSON)'}) + ORDER BY model; + + publish: + name: Upload when asked + start_on: + - compare + if: + condition: ${{inputs.hub_repo}} + true: upload + + upload: + tasks: + upload_model: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + source: ${{env.WORKFLOW_STORAGE}}/trained + token: ${{secrets.hf_token}} diff --git a/workflows/image-classification/README.md b/workflows/image-classification/README.md new file mode 100644 index 0000000..caf1515 --- /dev/null +++ b/workflows/image-classification/README.md @@ -0,0 +1,48 @@ +# Image classification + +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 +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` | +| 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` | +| Upload the model, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +**What stays one script:** the training loop, which holds the model, the +optimizer and the batches together on one GPU. + +The [classify images](../classify-images) workflow asks a vision-language +model the same question without training it; compare the two. + +## 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 `AI-Lab-Makerere/beans` | Parquet files or globs with a Hugging Face Image column, as DuckDB paths. | +| `image_column`, `label_column` | `image`, `labels` | The Image column and the label number column. | +| `labels` | `angular_leaf_spot,bean_rust,healthy` | Label names in label-number order. | +| `epochs` | `5` | Training epochs. | +| `examples_ref` | `main` | Branch, tag or full commit SHA of this repository whose scripts run. | +| `hub_repo` | empty | Hub 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 `metrics.json` with accuracy and macro F1. + +## Licenses + +- Model: [google/vit-base-patch16-224-in21k](https://huggingface.co/google/vit-base-patch16-224-in21k), Apache-2.0. +- Dataset: [AI-Lab-Makerere/beans](https://huggingface.co/datasets/AI-Lab-Makerere/beans), MIT. +- Packages the image step installs: NumPy (BSD-3-Clause), Pillow (MIT-CMU) and PyArrow (Apache-2.0). diff --git a/workflows/image-classification/pixels.py b/workflows/image-classification/pixels.py new file mode 100644 index 0000000..ee9c488 --- /dev/null +++ b/workflows/image-classification/pixels.py @@ -0,0 +1,21 @@ +"""Reads a split that preprocess.py prepared: memory-mapped pixel arrays and their labels.""" + +import json + +import numpy as np +import torch + + +class PreparedImages(torch.utils.data.Dataset): + def __init__(self, directory): + with open(f"{directory}/shape.json") as f: + shape = json.load(f) + self.pixels = np.memmap(f"{directory}/pixels.f32", dtype=np.float32, mode="r", + shape=(shape["count"], 3, shape["height"], shape["width"])) + self.labels = np.load(f"{directory}/labels.npy") + + def __len__(self): + return len(self.labels) + + def __getitem__(self, i): + return {"pixel_values": torch.from_numpy(np.array(self.pixels[i])), "labels": torch.tensor(self.labels[i])} diff --git a/workflows/image-classification/predict.py b/workflows/image-classification/predict.py new file mode 100644 index 0000000..75ae940 --- /dev/null +++ b/workflows/image-classification/predict.py @@ -0,0 +1,40 @@ +"""Predicts a label, or a number, for every prepared eval image, on a GPU. + +Writes the true and predicted values to Parquet; scoring them needs no GPU. +""" + +import argparse + +import numpy as np +import pyarrow as pa +import pyarrow.parquet as pq +import torch +from pixels import PreparedImages +from transformers import AutoModelForImageClassification + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Directory of the fine-tuned model") + p.add_argument("--data", required=True, help="Directory of the prepared eval split") + p.add_argument("--output", required=True, help="Parquet file the predictions are written to") + p.add_argument("--batch-size", type=int, default=64) + args = p.parse_args() + + model = AutoModelForImageClassification.from_pretrained(args.model).cuda().eval() + rows = PreparedImages(args.data) + predictions = [] + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): + for start in range(0, len(rows), args.batch_size): + pixels = torch.from_numpy(np.array(rows.pixels[start:start + args.batch_size])).cuda() + logits = model(pixel_values=pixels).logits + if model.config.num_labels == 1: + predictions += logits[:, 0].float().tolist() + else: + predictions += logits.argmax(-1).tolist() + pq.write_table(pa.table({"label": rows.labels.tolist(), "prediction": predictions}), args.output) + print(f"predicted {len(predictions)} images") + + +if __name__ == "__main__": + main() diff --git a/workflows/image-classification/preprocess.py b/workflows/image-classification/preprocess.py new file mode 100644 index 0000000..40a0c43 --- /dev/null +++ b/workflows/image-classification/preprocess.py @@ -0,0 +1,63 @@ +"""Checks, resizes and normalises 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 +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. +""" + +import argparse +import io +import json +import os + +import numpy as np +import pyarrow.parquet as pq +from PIL import Image + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Directory of the model, holding preprocessor_config.json") + p.add_argument("--train", required=True, help="Parquet file with image (bytes) and label columns") + p.add_argument("--eval", required=True, help="Parquet file with image (bytes) and label columns") + p.add_argument("--label-type", choices=["int", "float"], default="int") + p.add_argument("--output", required=True, help="Directory the prepared splits are written under") + args = p.parse_args() + + with open(f"{args.model}/preprocessor_config.json") as f: + config = json.load(f) + # Older configs give the size as one number, newer ones as height and width. + size = config.get("size", 224) + if isinstance(size, int): + height = width = size + else: + height, width = size.get("height", size.get("shortest_edge", 224)), size.get("width", size.get("shortest_edge", 224)) + mean = np.array(config.get("image_mean", [0.5, 0.5, 0.5]), dtype=np.float32)[:, None, None] + std = np.array(config.get("image_std", [0.5, 0.5, 0.5]), dtype=np.float32)[:, None, None] + + for name, path in [("train", args.train), ("eval", args.eval)]: + directory = f"{args.output}/{name}" + os.makedirs(directory, exist_ok=True) + labels, dropped = [], 0 + with open(f"{directory}/pixels.f32", "wb") as pixels: + for batch in pq.ParquetFile(path).iter_batches(columns=["image", "label"], batch_size=256): + for row in batch.to_pylist(): + try: + image = Image.open(io.BytesIO(row["image"]["bytes"])).convert("RGB") + except Exception: + dropped += 1 + continue + array = np.asarray(image.resize((width, height), Image.BICUBIC), dtype=np.float32) / 255.0 + pixels.write(((array.transpose(2, 0, 1) - mean) / std).astype(np.float32).tobytes()) + labels.append(row["label"]) + np.save(f"{directory}/labels.npy", np.array(labels, dtype=np.int64 if args.label_type == "int" else np.float32)) + with open(f"{directory}/shape.json", "w") as f: + json.dump({"count": len(labels), "height": height, "width": width}, f) + print(f"{name}: {len(labels)} images, {dropped} could not be decoded, {width}x{height}") + + +if __name__ == "__main__": + main() diff --git a/workflows/image-classification/train.py b/workflows/image-classification/train.py new file mode 100644 index 0000000..40a3e39 --- /dev/null +++ b/workflows/image-classification/train.py @@ -0,0 +1,65 @@ +"""Fine-tunes an image classification or regression model on prepared pixel arrays, 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. +""" + +import argparse + +from pixels import PreparedImages +from transformers import AutoImageProcessor, AutoModelForImageClassification, Trainer, TrainingArguments + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Hub repo id or directory of the model to fine-tune") + p.add_argument("--data", required=True, help="Directory holding the prepared train and eval splits") + p.add_argument("--labels", help="Label names, separated by commas, in label-number order") + p.add_argument("--regression", action="store_true", help="Predict one number per image instead of a class") + p.add_argument("--output", required=True, help="Directory the fine-tuned model is saved to") + p.add_argument("--epochs", type=float, default=5) + p.add_argument("--learning-rate", type=float, default=5e-5) + p.add_argument("--batch-size", type=int, default=32) + args = p.parse_args() + + if args.regression: + model = AutoModelForImageClassification.from_pretrained( + args.model, num_labels=1, problem_type="regression", ignore_mismatched_sizes=True) + else: + labels = args.labels.split(",") + model = AutoModelForImageClassification.from_pretrained( + args.model, + num_labels=len(labels), + id2label=dict(enumerate(labels)), + label2id={label: i for i, label in enumerate(labels)}, + ignore_mismatched_sizes=True, + ) + train = PreparedImages(f"{args.data}/train") + evaluation = PreparedImages(f"{args.data}/eval") + trainer = Trainer( + model=model, + args=TrainingArguments( + output_dir=f"{args.output}-checkpoints", + num_train_epochs=args.epochs, + learning_rate=args.learning_rate, + per_device_train_batch_size=args.batch_size, + per_device_eval_batch_size=args.batch_size, + eval_strategy="epoch", + save_strategy="no", + bf16=True, + # The pixels are already prepared and memory-mapped, so reading a batch is quick + # and needs no worker processes. + dataloader_num_workers=0, + remove_unused_columns=False, + report_to="none", + ), + train_dataset=train, + eval_dataset=evaluation, + ) + trainer.train() + trainer.save_model(args.output) + AutoImageProcessor.from_pretrained(args.model).save_pretrained(args.output) + + +if __name__ == "__main__": + main() diff --git a/workflows/image-classification/workflow.yaml b/workflows/image-classification/workflow.yaml new file mode 100644 index 0000000..c48cc08 --- /dev/null +++ b/workflows/image-classification/workflow.yaml @@ -0,0 +1,163 @@ +name: Image classification +description: Fine-tunes a vision transformer to classify images, with image checks and resizing on a CPU, training and prediction on a GPU, and accuracy and macro F1 computed in SQL. +compute_type: cpu-4 + +inputs: + model: + description: Hub 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/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/validation-00000-of-00001.parquet + image_column: + description: Image column, a struct holding the encoded image in its bytes field. + default: image + label_column: + description: Column holding the label, as a number from 0. + default: labels + labels: + description: Label names, separated by commas, in label-number order. + default: angular_leaf_spot,bean_rust,healthy + epochs: + description: Training epochs. + default: "5" + examples_ref: + description: Branch, tag or full commit SHA of swaleio/examples whose scripts run. + default: main + hub_repo: + description: Hub 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.label_column}}"::BIGINT AS label + FROM '${{inputs.train_data}}') + TO '${{env.WORKFLOW_STORAGE}}/train.parquet' (FORMAT parquet); + COPY (SELECT {'bytes': "${{inputs.image_column}}".bytes} AS image, "${{inputs.label_column}}"::BIGINT AS label + FROM '${{inputs.eval_data}}') + TO '${{env.WORKFLOW_STORAGE}}/eval.parquet' (FORMAT parquet); + SELECT 'train' AS split, label, count(*) AS images FROM '${{env.WORKFLOW_STORAGE}}/train.parquet' GROUP BY ALL + UNION ALL + SELECT 'eval', label, count(*) FROM '${{env.WORKFLOW_STORAGE}}/eval.parquet' GROUP BY ALL + ORDER BY split DESC, label; + + check_images: + name: Check, resize and normalise 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", "int", + "--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", + "--labels", "${{inputs.labels}}", "--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: | + CREATE TABLE predictions AS SELECT * FROM '${{env.WORKFLOW_STORAGE}}/predictions.parquet'; + CREATE TABLE per_class AS + WITH classes AS (SELECT DISTINCT label AS class FROM predictions) + SELECT string_split($$${{inputs.labels}}$$, ',')[class + 1] AS label, + sum((p.label = class AND p.prediction = class)::INT) AS tp, + sum((p.label <> class AND p.prediction = class)::INT) AS fp, + sum((p.label = class AND p.prediction <> class)::INT) AS fn + FROM classes, predictions p GROUP BY class ORDER BY class; + SELECT label, tp + fn AS rows, + round(CASE WHEN 2 * tp + fp + fn = 0 THEN 0 ELSE 2.0 * tp / (2 * tp + fp + fn) END, 4) AS f1 + FROM per_class; + COPY (SELECT (SELECT count(*) FROM predictions) AS rows, + (SELECT round(avg((label = prediction)::INT), 4) FROM predictions) AS accuracy, + (SELECT round(avg(CASE WHEN 2 * tp + fp + fn = 0 THEN 0 ELSE 2.0 * tp / (2 * tp + fp + fn) END), 4) FROM per_class) AS macro_f1) + 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 Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + source: ${{env.WORKFLOW_STORAGE}}/model + token: ${{secrets.hf_token}} diff --git a/workflows/image-regression/README.md b/workflows/image-regression/README.md new file mode 100644 index 0000000..1a06ba2 --- /dev/null +++ b/workflows/image-regression/README.md @@ -0,0 +1,48 @@ +# Image regression + +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` | `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` | +| 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` | +| Upload the model, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +The scripts are the [image classification](../image-classification) +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 | Hub 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`. + +## 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). diff --git a/workflows/image-regression/workflow.yaml b/workflows/image-regression/workflow.yaml new file mode 100644 index 0000000..3ff0f51 --- /dev/null +++ b/workflows/image-regression/workflow.yaml @@ -0,0 +1,154 @@ +name: 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: Hub 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: Hub 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 normalise 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 Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + source: ${{env.WORKFLOW_STORAGE}}/model + token: ${{secrets.hf_token}} diff --git a/workflows/kto-alignment/README.md b/workflows/kto-alignment/README.md new file mode 100644 index 0000000..298a999 --- /dev/null +++ b/workflows/kto-alignment/README.md @@ -0,0 +1,50 @@ +# Align a model with KTO + +Aligns a chat model with Kahneman-Tversky optimization, which learns from +single answers marked good or bad rather than from pairs, then checks that it +helped. TRL splits each preference pair of the default data into a good and a +bad answer. The base model and the aligned model both answer +the same held-out prompts, a judge model compares each pair of answers without +knowing which model wrote which, and the last step reports how often the +aligned model wins. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Write the training config | `swaleio/bash` | `cpu-4` | +| Fetch the base model, and the judge | `swaleio/hf-download` | `cpu-4` | +| Align the model | `swaleio/trl-kto` | `a100-1` | +| Write the held-out requests | `swaleio/duckdb` | `cpu-4` | +| Answer with the base model, and with the aligned model | `swaleio/vllm-batch` | `a100-1` each | +| Pair the answers, alternating their order, and write the judge requests | `swaleio/duckdb` | `cpu-4` | +| Judge each pair | `swaleio/vllm-batch` | `a100-1` | +| Count wins, losses and ties | `swaleio/duckdb` | `cpu-4` | +| Upload the aligned model, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +Every step is its own task. The base model answers while the aligned one is +still training. + +The whole model is trained, not a LoRA adapter, so vLLM can serve the result as +it is. A 0.5B model trains on one A100 this way; for larger models, add +`use_peft: true` to the config and merge the adapter before answering. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `model` | `Qwen/Qwen2.5-0.5B-Instruct` | Chat model to align. | +| `judge` | `Qwen/Qwen3-8B` | Judge model. | +| `train_split` | `train_prefs[:10000]` | Pairs of `HuggingFaceH4/ultrafeedback_binarized` to train on. | +| `eval_prompts` | `200` | Held-out prompts, from its `test_prefs` split. | +| `hub_repo` | empty | Hub model repo to upload the aligned model to. | + +The downloads, the training and the upload read the secret `hf_token`. + +## Output + +The aligned model in `aligned/` on the workspace, each judged pair in +`verdicts.parquet`, and the win rate in the last task's log. + +## Licenses of the defaults + +- Models: [Qwen/Qwen2.5-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct) and [Qwen/Qwen3-8B](https://huggingface.co/Qwen/Qwen3-8B), Apache-2.0. +- Dataset: [HuggingFaceH4/ultrafeedback_binarized](https://huggingface.co/datasets/HuggingFaceH4/ultrafeedback_binarized), MIT. diff --git a/workflows/kto-alignment/workflow.yaml b/workflows/kto-alignment/workflow.yaml new file mode 100644 index 0000000..d54edbc --- /dev/null +++ b/workflows/kto-alignment/workflow.yaml @@ -0,0 +1,201 @@ +name: Align a model with KTO +description: Aligns a chat model to answers labelled good or bad with TRL's KTO, then has a judge model compare its answers with the base model's on held-out prompts and reports the win rate. +compute_type: cpu-4 + +inputs: + model: + description: Hub repo id of the chat model to align. All of its weights are trained. + default: Qwen/Qwen2.5-0.5B-Instruct + judge: + description: Hub repo id of the judge model. + default: Qwen/Qwen3-8B + train_split: + description: Preference pairs to train on, from HuggingFaceH4/ultrafeedback_binarized; KTO splits each pair into a good and a bad answer. + default: train_prefs[:10000] + eval_prompts: + description: Number of held-out prompts the two models answer for the judge. + default: "200" + hub_repo: + description: Hub model repo to upload the aligned model to, as namespace/name. Leave empty to keep it on the workspace only. + default: "" + +entry_point: main + +blocks: + main: + tasks: + write_config: + name: Write training config + uses: swaleio/bash + args: + script: | + cat > "$WORKFLOW_STORAGE/kto.yaml" <//. + default: hf://datasets/google-research-datasets/poem_sentiment/data/test-00000-of-00001.parquet + text_column: + description: Column holding each text. + default: verse_text + labels: + description: The labels to choose from, separated by commas. The model can answer only with one of them. + default: negative,positive,no_impact,mixed + instruction: + description: What the model is told before each text. + default: Classify the sentiment of this line of poetry as negative, positive, no_impact (neither) or mixed. Answer with the label only. + gold_column: + description: Column holding existing labels, as each label's position in labels counting from 0, to measure agreement against. Leave empty when the texts have none. + default: label + limit: + description: Number of texts to label. + default: "1000" + hub_repo: + description: Hub dataset repo to upload the labels to, as namespace/name. Leave empty to keep them on the workspace only. + default: "" + +entry_point: main + +blocks: + main: + tasks: + model: + name: Fetch model + uses: swaleio/hf-download + args: + repo: ${{inputs.model}} + dest: ${{env.WORKFLOW_STORAGE}}/model + token: ${{secrets.hf_token}} + + requests: + name: Write requests + uses: swaleio/duckdb + args: + sql: | + CREATE TABLE texts AS + SELECT 'row-' || lpad((row_number() OVER () - 1)::VARCHAR, 6, '0') AS custom_id, * + FROM (SELECT * FROM '${{inputs.texts}}' LIMIT ${{inputs.limit}}); + COPY texts TO '${{env.WORKFLOW_STORAGE}}/texts.parquet' (FORMAT parquet); + COPY ( + SELECT custom_id, + 'POST' AS method, + '/v1/chat/completions' AS url, + {'model': '${{env.WORKFLOW_STORAGE}}/model', + 'messages': [{'role': 'system', 'content': $$${{inputs.instruction}}$$}, + {'role': 'user', 'content': "${{inputs.text_column}}"}], + 'max_tokens': 16, + 'temperature': 0, + 'structured_outputs': {'choice': string_split($$${{inputs.labels}}$$, ',')}} AS body + FROM texts + ) TO '${{env.WORKFLOW_STORAGE}}/requests.jsonl' (FORMAT json); + SELECT count(*) AS requests FROM texts; + + label: + name: Label + uses: swaleio/vllm-batch + compute_type: a100-1 + start_on: + - model + - requests + args: + model: ${{env.WORKFLOW_STORAGE}}/model + input_file: ${{env.WORKFLOW_STORAGE}}/requests.jsonl + output_file: ${{env.WORKFLOW_STORAGE}}/results.jsonl + + collect: + name: Collect labels + uses: swaleio/duckdb + start_on: + - label + args: + sql: | + CREATE TABLE labelled 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); + + compare: + name: Compare when existing labels are given + start_on: + - collect + if: + condition: ${{inputs.gold_column}} + true: agreement + + publish: + name: Upload when asked + start_on: + - compare + if: + condition: ${{inputs.hub_repo}} + true: upload + + agreement: + tasks: + measure: + name: Measure agreement + uses: swaleio/duckdb + args: + sql: | + CREATE TABLE pairs AS + SELECT string_split($$${{inputs.labels}}$$, ',')["${{inputs.gold_column}}" + 1] AS gold, llm_label + FROM '${{env.WORKFLOW_STORAGE}}/labels.parquet'; + SELECT count(*) AS texts, + round(avg((gold = llm_label)::INT), 3) AS agreement + FROM pairs; + PIVOT pairs ON llm_label USING count(*) GROUP BY gold ORDER BY gold; + + upload: + tasks: + upload_labels: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + repo_type: dataset + source: ${{env.WORKFLOW_STORAGE}}/labels.parquet + path_in_repo: data/labels.parquet + token: ${{secrets.hf_token}} diff --git a/workflows/llm-as-a-judge/README.md b/workflows/llm-as-a-judge/README.md new file mode 100644 index 0000000..68c1c9b --- /dev/null +++ b/workflows/llm-as-a-judge/README.md @@ -0,0 +1,41 @@ +# LLM as a judge + +Scores a model's answers with a stronger model. The model under test answers +every prompt; the judge reads each prompt and answer and rates the answer from +1 to 10; a last step prints the mean, the median and a histogram of the scores. +Run it on two models to compare them, or before and after a fine-tune. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Fetch the model, and the judge, in parallel | `swaleio/hf-download` | `cpu-4` | +| Write one answer request per prompt | `swaleio/duckdb` | `cpu-4` | +| 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` | + +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. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `model` | `Qwen/Qwen2.5-1.5B-Instruct` | Model whose answers are judged. | +| `judge` | `Qwen/Qwen3-8B` | Judge model. | +| `prompts` | the `test_prefs` split of `HuggingFaceH4/ultrafeedback_binarized` | Parquet file or glob, as a DuckDB path. | +| `prompt_column` | `prompt` | Column holding each prompt. | +| `limit` | `300` | Number of prompts. | +| `max_tokens` | `1024` | Longest answer. | + +The downloads read the secret `hf_token`. + +## Output + +`scored.parquet` on the workspace: each prompt, answer and score. The summary +is in the last task's log. + +## Licenses of the defaults + +- Models: [Qwen/Qwen2.5-1.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct) and [Qwen/Qwen3-8B](https://huggingface.co/Qwen/Qwen3-8B), Apache-2.0. +- Dataset: [HuggingFaceH4/ultrafeedback_binarized](https://huggingface.co/datasets/HuggingFaceH4/ultrafeedback_binarized), MIT. diff --git a/workflows/llm-as-a-judge/workflow.yaml b/workflows/llm-as-a-judge/workflow.yaml new file mode 100644 index 0000000..ee9df31 --- /dev/null +++ b/workflows/llm-as-a-judge/workflow.yaml @@ -0,0 +1,128 @@ +name: LLM as a judge +description: Answers a set of prompts with one model, has a stronger judge model score every answer from 1 to 10, and summarises the scores. +compute_type: cpu-4 + +inputs: + model: + description: Hub repo id of the model whose answers are judged. + default: Qwen/Qwen2.5-1.5B-Instruct + judge: + description: Hub repo id of the judge model. + default: Qwen/Qwen3-8B + prompts: + description: Parquet file or glob holding the prompts, as a DuckDB path. + default: hf://datasets/HuggingFaceH4/ultrafeedback_binarized/data/test_prefs-*.parquet + prompt_column: + description: Column holding each prompt. + default: prompt + limit: + description: Number of prompts. + default: "300" + max_tokens: + description: Longest answer, in tokens. + default: "1024" + +entry_point: main + +blocks: + main: + tasks: + fetch_model: + name: Fetch model + uses: swaleio/hf-download + args: + repo: ${{inputs.model}} + dest: ${{env.WORKFLOW_STORAGE}}/model + token: ${{secrets.hf_token}} + + fetch_judge: + name: Fetch judge + uses: swaleio/hf-download + args: + repo: ${{inputs.judge}} + dest: ${{env.WORKFLOW_STORAGE}}/judge + token: ${{secrets.hf_token}} + + requests: + name: Write answer requests + uses: swaleio/duckdb + args: + sql: | + CREATE TABLE prompts AS + SELECT 'p-' || lpad((row_number() OVER () - 1)::VARCHAR, 6, '0') AS custom_id, + "${{inputs.prompt_column}}" AS prompt + FROM (SELECT * FROM '${{inputs.prompts}}' LIMIT ${{inputs.limit}}); + COPY prompts TO '${{env.WORKFLOW_STORAGE}}/prompts.parquet' (FORMAT parquet); + COPY ( + SELECT custom_id, 'POST' AS method, '/v1/chat/completions' AS url, + {'model': '${{env.WORKFLOW_STORAGE}}/model', + 'messages': [{'role': 'user', 'content': prompt}], + 'max_tokens': ${{inputs.max_tokens}}} AS body + FROM prompts + ) TO '${{env.WORKFLOW_STORAGE}}/answer-requests.jsonl' (FORMAT json); + + answer: + name: Answer + uses: swaleio/vllm-batch + compute_type: a100-1 + start_on: + - fetch_model + - requests + args: + model: ${{env.WORKFLOW_STORAGE}}/model + input_file: ${{env.WORKFLOW_STORAGE}}/answer-requests.jsonl + output_file: ${{env.WORKFLOW_STORAGE}}/answers.jsonl + + judge_requests: + name: Write judge requests + uses: swaleio/duckdb + start_on: + - answer + args: + sql: | + CREATE TABLE answers AS + SELECT p.*, r.response.body.choices[1].message.content AS answer + FROM '${{env.WORKFLOW_STORAGE}}/prompts.parquet' p + JOIN read_json('${{env.WORKFLOW_STORAGE}}/answers.jsonl') r USING (custom_id); + COPY answers TO '${{env.WORKFLOW_STORAGE}}/answers.parquet' (FORMAT parquet); + COPY ( + SELECT custom_id, 'POST' AS method, '/v1/chat/completions' AS url, + {'model': '${{env.WORKFLOW_STORAGE}}/judge', + 'messages': [ + {'role': 'system', 'content': 'You grade answers. Rate how helpful, correct and clear the answer is for the request, from 1 (useless) to 10 (excellent). Reply with the number only.'}, + {'role': 'user', 'content': '[Request]\n' || prompt || '\n\n[Answer]\n' || answer}], + 'max_tokens': 4, 'temperature': 0, + 'chat_template_kwargs': {'enable_thinking': false}, + 'structured_outputs': {'choice': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']}} AS body + FROM answers + ) TO '${{env.WORKFLOW_STORAGE}}/judge-requests.jsonl' (FORMAT json); + + judge: + name: Judge + uses: swaleio/vllm-batch + compute_type: a100-1 + start_on: + - fetch_judge + - judge_requests + args: + model: ${{env.WORKFLOW_STORAGE}}/judge + input_file: ${{env.WORKFLOW_STORAGE}}/judge-requests.jsonl + output_file: ${{env.WORKFLOW_STORAGE}}/scores.jsonl + + summarise: + name: Summarise scores + uses: swaleio/duckdb + start_on: + - judge + args: + sql: | + CREATE TABLE scored AS + SELECT a.*, trim(s.response.body.choices[1].message.content)::INT AS score + FROM '${{env.WORKFLOW_STORAGE}}/answers.parquet' a + JOIN read_json('${{env.WORKFLOW_STORAGE}}/scores.jsonl') s USING (custom_id); + COPY scored TO '${{env.WORKFLOW_STORAGE}}/scored.parquet' (FORMAT parquet); + SELECT count(*) AS answers, round(avg(score), 2) AS mean_score, + median(score) AS median_score, sum((score >= 8)::INT) AS scored_8_or_more + FROM scored; + SELECT score, count(*) AS answers, repeat('#', count(*)::INT) AS bar + FROM scored GROUP BY score ORDER BY score; diff --git a/workflows/merge-models/README.md b/workflows/merge-models/README.md new file mode 100644 index 0000000..33b4995 --- /dev/null +++ b/workflows/merge-models/README.md @@ -0,0 +1,50 @@ +# Merge two fine-tunes + +Combines two fine-tunes of the same base model into one, without training. A +TIES merge keeps the largest changes each fine-tune made to the base weights, +settles their disagreements by sign, and adds them back to the base. The +merge and both parents are then scored on the same benchmark, side by side, so +you can see what the merge kept. The defaults merge Qwen's chat model with +NuMind's extraction model, both fine-tuned from Qwen2.5-0.5B. + +Both fine-tunes must come from `base` itself. A model built by long further +pretraining has moved too far from it: Qwen2.5-Coder-0.5B-Instruct, merged +with Qwen2.5-0.5B-Instruct this way, answered maths questions with strings of +zeros. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Write the merge config | `swaleio/bash` | `cpu-4` | +| Merge | `swaleio/mergekit` | `cpu-4` | +| Evaluate the merge, and each parent | `swaleio/lm-eval` | `a100-1` each | +| Compare the three scores | `swaleio/duckdb` | `cpu-4` | +| Upload the merge, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +Every step is its own task; the parents are scored while the merge runs. The +merge itself runs on the CPU. + +Merge only models whose licenses allow it, and give the merge a license that +respects both parents. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `base` | `Qwen/Qwen2.5-0.5B` | Base model of both fine-tunes. | +| `model_a` | `Qwen/Qwen2.5-0.5B-Instruct` | First fine-tune; the merge takes its tokenizer and chat template. | +| `model_b` | `numind/NuExtract-1.5-tiny` | Second fine-tune: NuMind's model for extracting structured data from text. | +| `eval_task` | `gsm8k` | lm-evaluation-harness task to score them on. | +| `hub_repo` | empty | Hub model repo to upload the merge to. | + +The merge, the parents' evaluations and the upload read the secret `hf_token`. + +## Output + +The merged model in `merged/` on the workspace, with a model card recording the +merge config, the scores in `eval/`, and the comparison in the last task's log. + +## Licenses of the defaults + +- Models: [Qwen/Qwen2.5-0.5B](https://huggingface.co/Qwen/Qwen2.5-0.5B) and [Qwen/Qwen2.5-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct), Apache-2.0; [numind/NuExtract-1.5-tiny](https://huggingface.co/numind/NuExtract-1.5-tiny), MIT. The merge carries both: Apache-2.0, keeping NuExtract's MIT notice. +- Evaluation data: [openai/gsm8k](https://huggingface.co/datasets/openai/gsm8k), MIT. +- The merge runs [mergekit](https://github.com/arcee-ai/mergekit), LGPL-3.0, inside `swaleio/mergekit`. diff --git a/workflows/merge-models/workflow.yaml b/workflows/merge-models/workflow.yaml new file mode 100644 index 0000000..23135b3 --- /dev/null +++ b/workflows/merge-models/workflow.yaml @@ -0,0 +1,128 @@ +name: Merge two fine-tunes +description: Merges two fine-tunes of one base model with mergekit's TIES method, scores the merge and both parents on the same benchmark, and uploads the merge. +compute_type: cpu-4 + +inputs: + base: + description: Hub repo id of the base model both fine-tunes come from. + default: Qwen/Qwen2.5-0.5B + model_a: + description: Hub repo id of the first fine-tune. + default: Qwen/Qwen2.5-0.5B-Instruct + model_b: + description: Hub repo id of the second fine-tune. + default: numind/NuExtract-1.5-tiny + eval_task: + description: The lm-evaluation-harness task the merge and both parents are scored on. + default: gsm8k + hub_repo: + description: Hub model repo to upload the merge to, as namespace/name. Leave empty to keep it on the workspace only. + default: "" + +entry_point: main + +blocks: + main: + tasks: + write_config: + name: Write merge config + uses: swaleio/bash + args: + script: | + cat > "$WORKFLOW_STORAGE/merge.yaml" < 'sample_len' + AND try_cast(value AS DOUBLE) IS NOT NULL) + ON model USING first(score) GROUP BY metric ORDER BY metric; + + publish: + name: Upload when asked + start_on: + - compare + if: + condition: ${{inputs.hub_repo}} + true: upload + + upload: + tasks: + upload_merge: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + source: ${{env.WORKFLOW_STORAGE}}/merged + token: ${{secrets.hf_token}} diff --git a/workflows/object-detection/README.md b/workflows/object-detection/README.md new file mode 100644 index 0000000..33c65aa --- /dev/null +++ b/workflows/object-detection/README.md @@ -0,0 +1,48 @@ +# Object detection + +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`](check_annotations.py)) | `swaleio/python-3-13` | `cpu-4` | +| Train ([`train.py`](train.py)) | `swaleio/transformers` | `a100-1` | +| Detect in the eval images ([`predict.py`](predict.py)) | `swaleio/transformers` | `a100-1` | +| Score mean average precision ([`score.py`](score.py)), and draw sample detections ([`draw.py`](draw.py)) | `swaleio/python-3-13` | `cpu-4` each | +| Upload the detector, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +**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 | Hub 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/`. + +## Licenses + +- Model: [PekingU/rtdetr_v2_r18vd](https://huggingface.co/PekingU/rtdetr_v2_r18vd), Apache-2.0. +- Dataset: [keremberke/construction-safety-object-detection](https://huggingface.co/datasets/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). diff --git a/workflows/object-detection/check_annotations.py b/workflows/object-detection/check_annotations.py new file mode 100644 index 0000000..8e4c94e --- /dev/null +++ b/workflows/object-detection/check_annotations.py @@ -0,0 +1,45 @@ +"""Checks bounding-box annotations and writes them in COCO format, on a CPU. + +Reads each split's Parquet file, with an image column and a Hugging Face-style +objects column (bbox as [x, y, width, height] in pixels, and category). A box +with no area, or one that reaches outside its image, is dropped and counted. +Writes .coco.json for each split, which training and scoring read. +""" + +import argparse +import io +import json + +import pyarrow.parquet as pq +from PIL import Image + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--splits", nargs="+", required=True, help="name=path.parquet for each split") + p.add_argument("--categories", required=True, help="Category names, separated by commas, in category-number order") + p.add_argument("--output", required=True, help="Directory the COCO files are written to") + args = p.parse_args() + + categories = [{"id": i, "name": name} for i, name in enumerate(args.categories.split(","))] + for spec in args.splits: + name, path = spec.split("=", 1) + table = pq.read_table(path).to_pylist() + images, annotations, dropped = [], [], 0 + for row in table: + width, height = Image.open(io.BytesIO(row["image"]["bytes"])).size + images.append({"id": row["image_id"], "width": width, "height": height}) + for bbox, category in zip(row["objects"]["bbox"], row["objects"]["category"]): + x, y, w, h = bbox + if w <= 0 or h <= 0 or x < 0 or y < 0 or x + w > width + 1 or y + h > height + 1: + dropped += 1 + continue + annotations.append({"id": len(annotations) + 1, "image_id": row["image_id"], "category_id": category, + "bbox": [x, y, w, h], "area": w * h, "iscrowd": 0}) + with open(f"{args.output}/{name}.coco.json", "w") as f: + json.dump({"images": images, "annotations": annotations, "categories": categories}, f) + print(f"{name}: {len(images)} images, {len(annotations)} boxes kept, {dropped} dropped") + + +if __name__ == "__main__": + main() diff --git a/workflows/object-detection/draw.py b/workflows/object-detection/draw.py new file mode 100644 index 0000000..7eeca70 --- /dev/null +++ b/workflows/object-detection/draw.py @@ -0,0 +1,43 @@ +"""Draws the detections above a score on a few eval images, on a CPU.""" + +import argparse +import io +import json +import os +from collections import defaultdict + +import pyarrow.parquet as pq +from PIL import Image, ImageDraw + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--images", required=True, help="Parquet file of eval images") + p.add_argument("--detections", required=True, help="Detections in COCO results format") + p.add_argument("--coco", required=True, help="COCO file whose categories name the labels") + p.add_argument("--output", required=True, help="Directory the drawn images are written to") + p.add_argument("--samples", type=int, default=8) + p.add_argument("--min-score", type=float, default=0.5) + args = p.parse_args() + + with open(args.coco) as f: + names = {c["id"]: c["name"] for c in json.load(f)["categories"]} + by_image = defaultdict(list) + with open(args.detections) as f: + for d in json.load(f): + if d["score"] >= args.min_score: + by_image[d["image_id"]].append(d) + os.makedirs(args.output, exist_ok=True) + for row in pq.read_table(args.images, columns=["image_id", "image"]).to_pylist()[:args.samples]: + image = Image.open(io.BytesIO(row["image"]["bytes"])).convert("RGB") + draw = ImageDraw.Draw(image) + for d in by_image[row["image_id"]]: + x, y, w, h = d["bbox"] + draw.rectangle([x, y, x + w, y + h], outline="red", width=3) + draw.text((x + 4, y + 4), f"{names[d['category_id']]} {d['score']:.2f}", fill="red") + image.save(f"{args.output}/{row['image_id']}.jpg") + print(row["image_id"], len(by_image[row["image_id"]]), "boxes") + + +if __name__ == "__main__": + main() diff --git a/workflows/object-detection/predict.py b/workflows/object-detection/predict.py new file mode 100644 index 0000000..13eb4d2 --- /dev/null +++ b/workflows/object-detection/predict.py @@ -0,0 +1,46 @@ +"""Detects objects in every eval image with the fine-tuned detector, on a GPU. + +Writes the detections in COCO results format, boxes as [x, y, width, height] in +pixels with a score, so scoring and drawing need no GPU. +""" + +import argparse +import io +import json + +import pyarrow.parquet as pq +import torch +from PIL import Image +from transformers import AutoImageProcessor, AutoModelForObjectDetection + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Directory of the fine-tuned detector") + p.add_argument("--images", required=True, help="Parquet file of eval images") + p.add_argument("--output", required=True, help="JSON file the detections are written to") + p.add_argument("--threshold", type=float, default=0.05, help="Lowest score kept") + args = p.parse_args() + + processor = AutoImageProcessor.from_pretrained(args.model) + model = AutoModelForObjectDetection.from_pretrained(args.model).cuda().eval() + detections = [] + with torch.no_grad(): + for row in pq.read_table(args.images, columns=["image_id", "image"]).to_pylist(): + image = Image.open(io.BytesIO(row["image"]["bytes"])).convert("RGB") + inputs = processor(images=image, return_tensors="pt").to("cuda") + outputs = model(**inputs) + result = processor.post_process_object_detection( + outputs, threshold=args.threshold, target_sizes=[(image.height, image.width)])[0] + for score, label, box in zip(result["scores"].tolist(), result["labels"].tolist(), result["boxes"].tolist()): + x1, y1, x2, y2 = box + detections.append({"image_id": row["image_id"], "category_id": label, + "bbox": [round(x1, 1), round(y1, 1), round(x2 - x1, 1), round(y2 - y1, 1)], + "score": round(score, 4)}) + with open(args.output, "w") as f: + json.dump(detections, f) + print(f"{len(detections)} detections") + + +if __name__ == "__main__": + main() diff --git a/workflows/object-detection/score.py b/workflows/object-detection/score.py new file mode 100644 index 0000000..e6068a0 --- /dev/null +++ b/workflows/object-detection/score.py @@ -0,0 +1,37 @@ +"""Scores detections with the COCO mean average precision, on a CPU, with pycocotools. + +Writes mAP over IoU thresholds 0.5 to 0.95, mAP at IoU 0.5 and 0.75, and recall +at 100 detections per image to a JSON file. +""" + +import argparse +import json + +from pycocotools.coco import COCO +from pycocotools.cocoeval import COCOeval + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--coco", required=True, help="COCO annotations of the eval images") + p.add_argument("--detections", required=True, help="Detections in COCO results format") + p.add_argument("--output", required=True, help="JSON file the scores are written to") + args = p.parse_args() + + truth = COCO(args.coco) + with open(args.detections) as f: + found = json.load(f) + evaluation = COCOeval(truth, truth.loadRes(found) if found else COCO(), "bbox") + evaluation.evaluate() + evaluation.accumulate() + evaluation.summarize() + stats = evaluation.stats + scores = {"map": round(stats[0], 4), "map_50": round(stats[1], 4), "map_75": round(stats[2], 4), + "recall_100": round(stats[8], 4), "detections": len(found)} + with open(args.output, "w") as f: + json.dump(scores, f, indent=2) + print(json.dumps(scores)) + + +if __name__ == "__main__": + main() diff --git a/workflows/object-detection/train.py b/workflows/object-detection/train.py new file mode 100644 index 0000000..a037db7 --- /dev/null +++ b/workflows/object-detection/train.py @@ -0,0 +1,90 @@ +"""Fine-tunes an object detector on images and COCO annotations, on a GPU. + +The image processor resizes each image and turns its boxes into the targets +the detector trains on. 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. +""" + +import argparse +import io +import json +from collections import defaultdict + +import pyarrow.parquet as pq +import torch +from PIL import Image +from transformers import AutoImageProcessor, AutoModelForObjectDetection, Trainer, TrainingArguments + + +class Detections(torch.utils.data.Dataset): + def __init__(self, parquet, coco, processor): + self.rows = pq.read_table(parquet, columns=["image_id", "image"]).to_pylist() + with open(coco) as f: + self.boxes = defaultdict(list) + for annotation in json.load(f)["annotations"]: + self.boxes[annotation["image_id"]].append(annotation) + self.processor = processor + + def __len__(self): + return len(self.rows) + + def __getitem__(self, i): + row = self.rows[i] + image = Image.open(io.BytesIO(row["image"]["bytes"])).convert("RGB") + target = {"image_id": row["image_id"], "annotations": self.boxes[row["image_id"]]} + encoded = self.processor(images=image, annotations=target, return_tensors="pt") + return {"pixel_values": encoded["pixel_values"][0], "labels": encoded["labels"][0]} + + +def collate(batch): + return {"pixel_values": torch.stack([b["pixel_values"] for b in batch]), "labels": [b["labels"] for b in batch]} + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Hub repo id or directory of the detector to fine-tune") + p.add_argument("--train", required=True, help="Parquet file of training images") + p.add_argument("--coco", required=True, help="COCO annotations of the training images") + p.add_argument("--categories", required=True, help="Category names, separated by commas, in category-number order") + p.add_argument("--output", required=True, help="Directory the fine-tuned detector is saved to") + p.add_argument("--epochs", type=float, default=30) + p.add_argument("--learning-rate", type=float, default=5e-5) + p.add_argument("--batch-size", type=int, default=8) + args = p.parse_args() + + categories = args.categories.split(",") + processor = AutoImageProcessor.from_pretrained(args.model) + model = AutoModelForObjectDetection.from_pretrained( + args.model, + num_labels=len(categories), + id2label=dict(enumerate(categories)), + label2id={name: i for i, name in enumerate(categories)}, + ignore_mismatched_sizes=True, + ) + trainer = Trainer( + model=model, + args=TrainingArguments( + output_dir=f"{args.output}-checkpoints", + num_train_epochs=args.epochs, + learning_rate=args.learning_rate, + per_device_train_batch_size=args.batch_size, + warmup_steps=100, + max_grad_norm=0.1, + save_strategy="no", + # Each image is decoded and resized as its batch is built, so worker processes + # prepare the next batches while the GPU trains on the current one. + dataloader_num_workers=4, + remove_unused_columns=False, + report_to="none", + ), + train_dataset=Detections(args.train, args.coco, processor), + data_collator=collate, + ) + trainer.train() + trainer.save_model(args.output) + processor.save_pretrained(args.output) + + +if __name__ == "__main__": + main() diff --git a/workflows/object-detection/workflow.yaml b/workflows/object-detection/workflow.yaml new file mode 100644 index 0000000..1ebf092 --- /dev/null +++ b/workflows/object-detection/workflow.yaml @@ -0,0 +1,170 @@ +name: Object detection +description: Fine-tunes an object detector on annotated images, with an annotation check and COCO conversion on a CPU, training and detection on a GPU, and COCO mean average precision and sample drawings on a CPU. +compute_type: cpu-4 + +inputs: + model: + description: Hub 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: Hub 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 Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + source: ${{env.WORKFLOW_STORAGE}}/model + token: ${{secrets.hf_token}} diff --git a/workflows/ocr-pages/README.md b/workflows/ocr-pages/README.md new file mode 100644 index 0000000..ef6341e --- /dev/null +++ b/workflows/ocr-pages/README.md @@ -0,0 +1,44 @@ +# OCR pages with a vision-language model + +Transcribes a PDF page by page with a vision-language model: each page is +rendered to an image, the model writes out the page as Markdown, and the pages +are joined into one document. This suits scans and layouts a text extractor +cannot read. For born-digital PDFs, `swaleio/docling` is faster and keeps the +document's structure; see the [PDFs to Markdown](../pdfs-to-markdown) workflow. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Fetch the model | `swaleio/hf-download` | `cpu-4` | +| Fetch the PDF | `swaleio/http-request` | `cpu-4` | +| Render each page to PNG | `swaleio/python-3-13` | `cpu-4` | +| Write one request per page, with the page inline | `swaleio/duckdb` | `cpu-4` | +| Transcribe | `swaleio/vllm-batch` | `a100-1` | +| Join the pages into one Markdown document | `swaleio/duckdb` | `cpu-4` | + +Every step is its own task; only transcription holds a GPU. + +The last step prints each page's `finish_reason`. `length` means the page ran +into the token limit. With the default 2B model that happens on dense pages, +such as a list of references, where the model starts repeating itself. A larger +model, such as `Qwen/Qwen3-VL-8B-Instruct`, reads those pages better. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `pdf_url` | the Docling technical report on arXiv | URL of the PDF. | +| `model` | `Qwen/Qwen3-VL-2B-Instruct` | Vision-language model on the Hub that vLLM serves. | +| `dpi` | `110` | Resolution the pages are rendered at. | + +The download reads the secret `hf_token`. + +## Output + +`document.md` on the workspace, with the pages separated by `---`, and +`pages.parquet` with each page's Markdown and `finish_reason`. + +## Licenses of the defaults + +- Model: [Qwen/Qwen3-VL-2B-Instruct](https://huggingface.co/Qwen/Qwen3-VL-2B-Instruct), Apache-2.0. +- Document: [Docling Technical Report](https://arxiv.org/abs/2408.09869), CC BY 4.0. +- Packages the render step installs: pypdfium2 (Apache-2.0 or BSD-3-Clause; PDFium is BSD-3-Clause) and Pillow (MIT-CMU). diff --git a/workflows/ocr-pages/workflow.yaml b/workflows/ocr-pages/workflow.yaml new file mode 100644 index 0000000..f7426c9 --- /dev/null +++ b/workflows/ocr-pages/workflow.yaml @@ -0,0 +1,104 @@ +name: OCR pages with a vision-language model +description: Renders each page of a PDF to an image and has a vision-language model transcribe every page to Markdown, then joins the pages into one document. +compute_type: cpu-4 + +inputs: + pdf_url: + description: URL of the PDF to transcribe. + default: https://arxiv.org/pdf/2408.09869v5 + model: + description: Hub repo id of the vision-language model that reads the pages. + default: Qwen/Qwen3-VL-2B-Instruct + dpi: + description: Resolution the pages are rendered at. + default: "110" + +entry_point: main + +blocks: + main: + tasks: + fetch_model: + name: Fetch model + uses: swaleio/hf-download + args: + repo: ${{inputs.model}} + dest: ${{env.WORKFLOW_STORAGE}}/model + token: ${{secrets.hf_token}} + + fetch_pdf: + name: Fetch PDF + uses: swaleio/http-request + args: + url: ${{inputs.pdf_url}} + expected_status: "200" + response_path: ${{env.WORKFLOW_STORAGE}}/document.pdf + + render: + name: Render pages + uses: swaleio/python-3-13 + start_on: + - fetch_pdf + args: + script: | + import os, subprocess, sys + subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "--target", "/tmp/deps", + "pypdfium2==5.15.2", "pillow==13.0.0"], check=True) + sys.path.insert(0, "/tmp/deps") + import pypdfium2 as pdfium + + storage = os.environ["WORKFLOW_STORAGE"] + out = os.path.join(storage, "pages") + os.makedirs(out, exist_ok=True) + pdf = pdfium.PdfDocument(os.path.join(storage, "document.pdf")) + for number, page in enumerate(pdf, 1): + page.render(scale=${{inputs.dpi}} / 72).to_pil().save(os.path.join(out, f"{number:04d}.png")) + print(f"rendered {len(pdf)} pages") + + requests: + name: Write page requests + uses: swaleio/duckdb + start_on: + - render + args: + sql: | + COPY ( + SELECT 'page-' || regexp_extract(filename, '(\d+)\.png$', 1) AS custom_id, + 'POST' AS method, '/v1/chat/completions' AS url, + {'model': '${{env.WORKFLOW_STORAGE}}/model', + 'messages': [{'role': 'user', 'content': [ + {'type': 'image_url', 'image_url': {'url': 'data:image/png;base64,' || base64(content)}}, + {'type': 'text', 'text': 'Read this page and write out all of its text as plain Markdown, in reading order, with its headings, lists and tables. Do not use LaTeX. Write nothing else.'}]}], + 'max_tokens': 4096, 'temperature': 0, 'repetition_penalty': 1.05} AS body + FROM read_blob('${{env.WORKFLOW_STORAGE}}/pages/*.png') + ) TO '${{env.WORKFLOW_STORAGE}}/requests.jsonl' (FORMAT json); + SELECT count(*) AS pages FROM read_blob('${{env.WORKFLOW_STORAGE}}/pages/*.png'); + + transcribe: + name: Transcribe pages + uses: swaleio/vllm-batch + compute_type: a100-1 + start_on: + - fetch_model + - requests + args: + model: ${{env.WORKFLOW_STORAGE}}/model + input_file: ${{env.WORKFLOW_STORAGE}}/requests.jsonl + output_file: ${{env.WORKFLOW_STORAGE}}/pages.jsonl + + assemble: + name: Assemble document + uses: swaleio/duckdb + start_on: + - transcribe + args: + sql: | + CREATE TABLE pages AS + SELECT custom_id AS page, + response.body.choices[1].message.content AS markdown, + response.body.choices[1].finish_reason AS finish_reason + FROM read_json('${{env.WORKFLOW_STORAGE}}/pages.jsonl') ORDER BY page; + COPY pages TO '${{env.WORKFLOW_STORAGE}}/pages.parquet' (FORMAT parquet); + COPY (SELECT string_agg(markdown, chr(10) || chr(10) || '---' || chr(10) || chr(10) ORDER BY page) FROM pages) + TO '${{env.WORKFLOW_STORAGE}}/document.md' (FORMAT csv, HEADER false, QUOTE '', ESCAPE ''); + SELECT page, finish_reason, length(markdown) AS characters FROM pages; diff --git a/workflows/pdfs-to-markdown/README.md b/workflows/pdfs-to-markdown/README.md new file mode 100644 index 0000000..478e58d --- /dev/null +++ b/workflows/pdfs-to-markdown/README.md @@ -0,0 +1,39 @@ +# PDFs to a Markdown dataset + +Turns a list of PDFs into a text dataset. Each PDF is fetched and converted to +Markdown by Docling in its own pair of tasks, and all the pairs run at the same +time; a last step gathers the Markdown files into one Parquet file with each +document's source URL. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| For each PDF: fetch it | `swaleio/http-request` | `cpu-4` | +| For each PDF: convert it to Markdown, pictures marked by placeholders | `swaleio/docling` | `cpu-4` | +| Gather the Markdown into `documents.parquet` | `swaleio/duckdb` | `cpu-4` | +| Upload to the Hub, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +Every step is its own task. Docling converts a 10-page paper in under a minute +on a CPU compute type; give the convert task a GPU compute type for long +documents. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `pdf_urls` | three papers from arXiv | The PDFs, as a JSON array of URLs. | +| `hub_repo` | empty | Hub dataset repo to upload the dataset to, as `data/train.parquet`. | + +The upload reads the secret `hf_token`. + +## Output + +`documents.parquet` on the workspace, with `url`, `markdown` and `characters` +for each PDF, and the Markdown files in `markdown/`. + +## Licenses of the defaults + +The three default PDFs are licensed CC BY 4.0 by their authors: +[Docling Technical Report](https://arxiv.org/abs/2408.09869), +[Docling: An Efficient Open-Source Toolkit for AI-driven Document Conversion](https://arxiv.org/abs/2501.17887) +and [QLoRA: Efficient Finetuning of Quantized LLMs](https://arxiv.org/abs/2305.14314). +A dataset made from them keeps their attribution. diff --git a/workflows/pdfs-to-markdown/workflow.yaml b/workflows/pdfs-to-markdown/workflow.yaml new file mode 100644 index 0000000..4ffff36 --- /dev/null +++ b/workflows/pdfs-to-markdown/workflow.yaml @@ -0,0 +1,79 @@ +name: PDFs to a Markdown dataset +description: Converts a list of PDFs to Markdown with Docling, one task per document, and collects the results into one Parquet dataset. +compute_type: cpu-4 + +inputs: + pdf_urls: + description: The PDFs to convert, as a JSON array of URLs. + default: '["https://arxiv.org/pdf/2408.09869v5", "https://arxiv.org/pdf/2501.17887v1", "https://arxiv.org/pdf/2305.14314v1"]' + hub_repo: + description: Hub dataset repo to upload the dataset to, as namespace/name. Leave empty to keep it on the workspace only. + default: "" + +entry_point: main + +blocks: + main: + tasks: + each_pdf: + name: Convert each PDF + for_each: + items: ${{inputs.pdf_urls}} + block: convert_one + + collect: + name: Collect into a dataset + uses: swaleio/duckdb + start_on: + - each_pdf + args: + sql: | + CREATE TABLE documents AS + WITH urls AS ( + SELECT unnest(from_json($$${{inputs.pdf_urls}}$$, '["VARCHAR"]')) AS url, + generate_subscripts(from_json($$${{inputs.pdf_urls}}$$, '["VARCHAR"]'), 1) - 1 AS item) + SELECT u.url, t.content AS markdown, length(t.content) AS characters + FROM read_text('${{env.WORKFLOW_STORAGE}}/markdown/*.md') t + JOIN urls u ON regexp_extract(t.filename, '(\d+)\.md$', 1)::INT = u.item + ORDER BY u.item; + SELECT url, characters FROM documents; + COPY documents TO '${{env.WORKFLOW_STORAGE}}/documents.parquet' (FORMAT parquet); + + publish: + name: Upload when asked + start_on: + - collect + if: + condition: ${{inputs.hub_repo}} + true: upload + + convert_one: + tasks: + fetch: + name: Fetch PDF + uses: swaleio/http-request + args: + url: ${{tasks.each_pdf.for_each.item}} + expected_status: "200" + response_path: ${{env.WORKFLOW_STORAGE}}/pdf/${{tasks.each_pdf.for_each.index}}.pdf + convert: + name: Convert to Markdown + uses: swaleio/docling + start_on: + - fetch + args: + source: ${{env.WORKFLOW_STORAGE}}/pdf/${{tasks.each_pdf.for_each.index}}.pdf + output_dir: ${{env.WORKFLOW_STORAGE}}/markdown + image_export_mode: placeholder + + upload: + tasks: + upload_dataset: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + repo_type: dataset + source: ${{env.WORKFLOW_STORAGE}}/documents.parquet + path_in_repo: data/train.parquet + token: ${{secrets.hf_token}} diff --git a/workflows/quantize-and-pick/README.md b/workflows/quantize-and-pick/README.md new file mode 100644 index 0000000..c031202 --- /dev/null +++ b/workflows/quantize-and-pick/README.md @@ -0,0 +1,47 @@ +# Quantize and pick + +Finds the smallest quantized version of a model that still holds up. The model +is converted to a 16-bit GGUF file once; then each quantization preset is +made, measured for perplexity on the same text and benchmarked for speed in its +own tasks, all presets at the same time. A last step compares every preset's +size and perplexity with the 16-bit file's and keeps the smallest one whose +perplexity rose by no more than `max_increase` percent. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Fetch the model | `swaleio/hf-download` | `cpu-4` | +| Write the measuring text | `swaleio/duckdb` | `cpu-4` | +| Make the output folders | `swaleio/bash` | `cpu-4` | +| Convert to a 16-bit GGUF file | `swaleio/llamacpp-convert` | `cpu-4` | +| Measure the 16-bit file's perplexity | `swaleio/llamacpp-perplexity` | `a100-1` | +| For each preset: quantize | `swaleio/llamacpp-quantize` | `cpu-4` | +| For each preset: measure perplexity, and benchmark speed | `swaleio/llamacpp-perplexity`, `swaleio/llamacpp-bench` | `a100-1` each | +| Compare sizes and perplexities, pick the preset | `swaleio/duckdb` | `cpu-4` | +| Stage the chosen file | `swaleio/bash` | `cpu-4` | +| Upload it, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +Every step is its own task. The pick reads perplexity from the log file +`llamacpp-perplexity` writes. `llama-bench` prints its speeds only to its task +log, so they are there to read but do not take part in the pick. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `model` | `Qwen/Qwen2.5-1.5B-Instruct` | Model to quantize. | +| `presets` | `Q3_K_M`, `Q4_K_M`, `Q5_K_M`, `Q6_K`, `Q8_0` | llama.cpp presets to try, as a JSON array. | +| `max_increase` | `5` | Largest perplexity increase over the 16-bit file the chosen preset may have, in percent. | +| `hub_repo` | empty | Hub model repo to upload the chosen file to. | + +The download and the upload read the secret `hf_token`. + +## Output + +Every GGUF file in `gguf/` on the workspace, the perplexity logs in `logs/`, +and the chosen file in `release/`. The comparison table is in the pick task's +log. + +## Licenses of the defaults + +- Model: [Qwen/Qwen2.5-1.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct), Apache-2.0. +- Measuring text: questions and answers of [openai/gsm8k](https://huggingface.co/datasets/openai/gsm8k), MIT. diff --git a/workflows/quantize-and-pick/workflow.yaml b/workflows/quantize-and-pick/workflow.yaml new file mode 100644 index 0000000..fa048b0 --- /dev/null +++ b/workflows/quantize-and-pick/workflow.yaml @@ -0,0 +1,165 @@ +name: Quantize and pick +description: Converts a model to GGUF, quantizes it to several presets in parallel, measures each preset's perplexity and speed, and uploads the smallest one within a perplexity budget. +compute_type: cpu-4 + +inputs: + model: + description: Hub repo id of the model to quantize. + default: Qwen/Qwen2.5-1.5B-Instruct + presets: + description: llama.cpp quantization presets to try, as a JSON array. + default: '["Q3_K_M", "Q4_K_M", "Q5_K_M", "Q6_K", "Q8_0"]' + max_increase: + description: Largest perplexity increase over the 16-bit file that the chosen preset may have, in percent. + default: "5" + hub_repo: + description: Hub model repo to upload the chosen file to, as namespace/name. Leave empty to keep it on the workspace only. + default: "" + +entry_point: main + +blocks: + main: + tasks: + fetch: + name: Fetch the model + uses: swaleio/hf-download + args: + repo: ${{inputs.model}} + dest: ${{env.WORKFLOW_STORAGE}}/hf + token: ${{secrets.hf_token}} + + text: + name: Write the measuring text + uses: swaleio/duckdb + args: + sql: | + COPY (SELECT question || ' ' || answer + FROM 'hf://datasets/openai/gsm8k/main/test-*.parquet' LIMIT 300) + TO '${{env.WORKFLOW_STORAGE}}/measure.txt' (FORMAT csv, HEADER false, QUOTE '', DELIMITER '\t'); + + make_dirs: + name: Make output folders + uses: swaleio/bash + args: + script: mkdir -p "$WORKFLOW_STORAGE/gguf" "$WORKFLOW_STORAGE/logs" "$WORKFLOW_STORAGE/release" + + convert: + name: Convert to a 16-bit GGUF file + uses: swaleio/llamacpp-convert + start_on: + - fetch + - make_dirs + args: + model_dir: ${{env.WORKFLOW_STORAGE}}/hf + outfile: ${{env.WORKFLOW_STORAGE}}/gguf/model-16bit.gguf + + measure_16bit: + name: Measure the 16-bit file + uses: swaleio/llamacpp-perplexity + compute_type: a100-1 + start_on: + - convert + - text + args: + model: ${{env.WORKFLOW_STORAGE}}/gguf/model-16bit.gguf + text_file: ${{env.WORKFLOW_STORAGE}}/measure.txt + log_file: ${{env.WORKFLOW_STORAGE}}/logs/16bit.log + + each_preset: + name: Quantize and measure each preset + start_on: + - convert + - text + for_each: + items: ${{inputs.presets}} + block: one_preset + + pick: + name: Pick the preset + uses: swaleio/duckdb + start_on: + - measure_16bit + - each_preset + args: + sql: | + -- llama-perplexity ends its log with "Final estimate: PPL = +/- ". + CREATE TABLE measured AS + SELECT regexp_extract(filename, '/([^/]+)\.log$', 1) AS preset, + regexp_extract(content, 'Final estimate: PPL = ([0-9.]+)', 1)::DOUBLE AS perplexity + FROM read_text('${{env.WORKFLOW_STORAGE}}/logs/*.log'); + CREATE TABLE sizes AS + SELECT regexp_extract(filename, 'model-([^/]+)\.gguf$', 1) AS preset, round(size / 1e6) AS megabytes + FROM read_blob('${{env.WORKFLOW_STORAGE}}/gguf/*.gguf'); + CREATE TABLE compared AS + SELECT m.preset, s.megabytes, m.perplexity, + round(100 * (m.perplexity / (SELECT perplexity FROM measured WHERE preset = '16bit') - 1), 2) AS increase_percent + FROM measured m JOIN sizes s USING (preset) + ORDER BY s.megabytes; + SELECT * FROM compared; + CREATE TABLE chosen AS + SELECT preset FROM compared + WHERE preset <> '16bit' AND increase_percent <= ${{inputs.max_increase}} + ORDER BY megabytes LIMIT 1; + SELECT preset AS chosen FROM chosen; + COPY (SELECT 'model-' || preset || '.gguf' FROM chosen) + TO '${{env.WORKFLOW_STORAGE}}/chosen.txt' (FORMAT csv, HEADER false, QUOTE ''); + + stage: + name: Stage the chosen file + uses: swaleio/bash + start_on: + - pick + args: + script: | + set -euo pipefail + chosen=$(cat "$WORKFLOW_STORAGE/chosen.txt") + [ -n "$chosen" ] || { echo "no preset is within ${{inputs.max_increase}}% of the 16-bit perplexity" >&2; exit 1; } + cp "$WORKFLOW_STORAGE/gguf/$chosen" "$WORKFLOW_STORAGE/release/" + echo "chosen: $chosen" + + publish: + name: Upload when asked + start_on: + - stage + if: + condition: ${{inputs.hub_repo}} + true: upload + + one_preset: + tasks: + quantize: + name: Quantize + uses: swaleio/llamacpp-quantize + args: + input_gguf: ${{env.WORKFLOW_STORAGE}}/gguf/model-16bit.gguf + output_gguf: ${{env.WORKFLOW_STORAGE}}/gguf/model-${{tasks.each_preset.for_each.item}}.gguf + preset: ${{tasks.each_preset.for_each.item}} + measure: + name: Measure perplexity + uses: swaleio/llamacpp-perplexity + compute_type: a100-1 + start_on: + - quantize + args: + model: ${{env.WORKFLOW_STORAGE}}/gguf/model-${{tasks.each_preset.for_each.item}}.gguf + text_file: ${{env.WORKFLOW_STORAGE}}/measure.txt + log_file: ${{env.WORKFLOW_STORAGE}}/logs/${{tasks.each_preset.for_each.item}}.log + bench: + name: Benchmark speed + uses: swaleio/llamacpp-bench + compute_type: a100-1 + start_on: + - quantize + args: + model: ${{env.WORKFLOW_STORAGE}}/gguf/model-${{tasks.each_preset.for_each.item}}.gguf + + upload: + tasks: + upload_gguf: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + source: ${{env.WORKFLOW_STORAGE}}/release + token: ${{secrets.hf_token}} diff --git a/workflows/retrieval-index/README.md b/workflows/retrieval-index/README.md new file mode 100644 index 0000000..fb4f334 --- /dev/null +++ b/workflows/retrieval-index/README.md @@ -0,0 +1,46 @@ +# Build a retrieval index + +Builds the index a retrieval-augmented generation (RAG) application searches. +Each PDF is fetched and split into chunks of text by Docling, all PDFs at the +same time; Text Embeddings Inference embeds every chunk; DuckDB stores chunks +and vectors in one Parquet file; and a test query is answered from it with +cosine similarity, to show the index works. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| For each PDF: fetch it | `swaleio/http-request` | `cpu-4` | +| For each PDF: convert it to chunks | `swaleio/docling` | `cpu-4` | +| Serve the embedding model, as a runner | `swaleio/tei-serve` | `a100-1` | +| Wait for the server, checking every 5 seconds | `swaleio/http-request` | `cpu-4` | +| Embed the chunks, 32 per request | `swaleio/python-3-13` | `cpu-4` | +| Embed the test query | `swaleio/http-request` | `cpu-4` | +| Write `index.parquet`, count chunks per document | `swaleio/duckdb` | `cpu-4` | +| Find the five chunks closest to the query | `swaleio/duckdb` | `cpu-4` | +| Upload the index, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +Every step is its own task. The embedding client is a short Python script inside +the workflow that uses only the standard library. Docling counts each chunk's +tokens with a tokenizer it downloads from the Hub. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `pdf_urls` | three papers from arXiv | The PDFs, as a JSON array of URLs. | +| `model` | `BAAI/bge-small-en-v1.5` | Embedding model; the query must be embedded with the same one. | +| `query` | a question about Docling's tables | A question to test the index with; leave double quotes out of it. | +| `hub_repo` | empty | Hub dataset repo to upload the index to, as `data/train.parquet`. | + +The upload reads the secret `hf_token`. + +## Output + +`index.parquet` on the workspace, with `url`, `chunk`, `text` and `embedding` +for every chunk. The five closest chunks to the query are in the search task's +log. + +## Licenses of the defaults + +- Embedding model: [BAAI/bge-small-en-v1.5](https://huggingface.co/BAAI/bge-small-en-v1.5), MIT. +- Chunking tokenizer: [sentence-transformers/all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2), Apache-2.0. +- Documents: three arXiv papers licensed CC BY 4.0 by their authors, listed in the [PDFs to Markdown](../pdfs-to-markdown) workflow. An index of them keeps their attribution. diff --git a/workflows/retrieval-index/workflow.yaml b/workflows/retrieval-index/workflow.yaml new file mode 100644 index 0000000..c8d0fdd --- /dev/null +++ b/workflows/retrieval-index/workflow.yaml @@ -0,0 +1,169 @@ +name: Build a retrieval index +description: Converts PDFs to chunks of text with Docling, embeds every chunk with Text Embeddings Inference, stores chunks and vectors as a Parquet index, and answers a test query from it. +compute_type: cpu-4 + +inputs: + pdf_urls: + description: The PDFs to index, as a JSON array of URLs. + default: '["https://arxiv.org/pdf/2408.09869v5", "https://arxiv.org/pdf/2501.17887v1", "https://arxiv.org/pdf/2305.14314v1"]' + model: + description: Hub repo id of the embedding model. + default: BAAI/bge-small-en-v1.5 + query: + description: A question to test the index with. + default: How does Docling recognise the structure of tables? + hub_repo: + description: Hub dataset repo to upload the index to, as namespace/name. Leave empty to keep it on the workspace only. + default: "" + +entry_point: main + +blocks: + main: + tasks: + each_pdf: + name: Chunk each PDF + for_each: + items: ${{inputs.pdf_urls}} + block: chunk_one + + serve: + name: Serve the embedding model + uses: swaleio/tei-serve + compute_type: a100-1 + terminate_on: + - embed_chunks + - embed_query + args: + model: ${{inputs.model}} + + wait_ready: + name: Wait for the server + uses: swaleio/http-request + start_on: + - serve + args: + url: http://${{tasks.serve.ip-address}}:8080/health + retry: "360" + retry_delay: "5" + expected_status: "200" + + embed_chunks: + name: Embed the chunks + uses: swaleio/python-3-13 + start_on: + - wait_ready + - each_pdf + args: + script: | + import glob, json, os, urllib.request + + storage = os.environ["WORKFLOW_STORAGE"] + server = "http://${{tasks.serve.ip-address}}:8080/embed" + chunks = [] + for path in sorted(glob.glob(f"{storage}/chunks/*.jsonl")): + with open(path) as f: + chunks += [json.loads(line) for line in f if line.strip()] + + def embed(texts): + body = json.dumps({"inputs": texts, "truncate": True}).encode() + request = urllib.request.Request(server, body, {"Content-Type": "application/json"}) + with urllib.request.urlopen(request, timeout=300) as response: + return json.load(response) + + with open(f"{storage}/chunk-vectors.jsonl", "w") as out: + for start in range(0, len(chunks), 32): + batch = chunks[start:start + 32] + for chunk, vector in zip(batch, embed([c["text"] for c in batch])): + out.write(json.dumps({"document": chunk["filename"], "chunk": chunk["chunk_index"], + "text": chunk["text"], "embedding": vector}) + "\n") + print(f"embedded {len(chunks)} chunks") + + embed_query: + name: Embed the test query + uses: swaleio/http-request + start_on: + - wait_ready + args: + url: http://${{tasks.serve.ip-address}}:8080/embed + method: POST + headers: | + Content-Type: application/json + body: '{"inputs": "${{inputs.query}}", "truncate": true}' + expected_status: "200" + response_path: ${{env.WORKFLOW_STORAGE}}/query-vector.json + + index: + name: Write the index + uses: swaleio/duckdb + start_on: + - embed_chunks + args: + sql: | + CREATE TABLE sources AS + SELECT unnest(from_json($$${{inputs.pdf_urls}}$$, '["VARCHAR"]')) AS url, + (generate_subscripts(from_json($$${{inputs.pdf_urls}}$$, '["VARCHAR"]'), 1) - 1)::VARCHAR AS document; + CREATE TABLE chunks AS + SELECT s.url, c.chunk, c.text, c.embedding::FLOAT[] AS embedding + FROM read_json('${{env.WORKFLOW_STORAGE}}/chunk-vectors.jsonl', + columns = {'document': 'VARCHAR', 'chunk': 'INTEGER', 'text': 'VARCHAR', 'embedding': 'DOUBLE[]'}) c + JOIN sources s USING (document) + ORDER BY s.url, c.chunk; + COPY chunks TO '${{env.WORKFLOW_STORAGE}}/index.parquet' (FORMAT parquet); + SELECT url, count(*) AS chunks FROM chunks GROUP BY url ORDER BY url; + + search: + name: Answer the test query + uses: swaleio/duckdb + start_on: + - index + - embed_query + args: + sql: | + -- The server answers /embed with one vector per input, so the query's is the first. + CREATE TABLE query AS + SELECT json_extract(json, '$[0]')::FLOAT[] AS vector + FROM read_json_objects('${{env.WORKFLOW_STORAGE}}/query-vector.json', format = 'unstructured'); + SELECT round(list_cosine_similarity(c.embedding, q.vector), 3) AS similarity, + c.url, c.chunk, left(replace(c.text, chr(10), ' '), 160) AS text + FROM '${{env.WORKFLOW_STORAGE}}/index.parquet' c, query q + ORDER BY similarity DESC LIMIT 5; + + publish: + name: Upload when asked + start_on: + - search + if: + condition: ${{inputs.hub_repo}} + true: upload + + chunk_one: + tasks: + fetch: + name: Fetch PDF + uses: swaleio/http-request + args: + url: ${{tasks.each_pdf.for_each.item}} + expected_status: "200" + response_path: ${{env.WORKFLOW_STORAGE}}/pdf/${{tasks.each_pdf.for_each.index}}.pdf + chunk: + name: Convert to chunks + uses: swaleio/docling + start_on: + - fetch + args: + source: ${{env.WORKFLOW_STORAGE}}/pdf/${{tasks.each_pdf.for_each.index}}.pdf + output_dir: ${{env.WORKFLOW_STORAGE}}/chunks + to: chunks + + upload: + tasks: + upload_index: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + repo_type: dataset + source: ${{env.WORKFLOW_STORAGE}}/index.parquet + path_in_repo: data/train.parquet + token: ${{secrets.hf_token}} diff --git a/workflows/reward-model/README.md b/workflows/reward-model/README.md new file mode 100644 index 0000000..eecdcbd --- /dev/null +++ b/workflows/reward-model/README.md @@ -0,0 +1,41 @@ +# Train a reward model + +Trains a reward model, the scorer that RLHF methods and best-of-n sampling +rank answers with, on human preference pairs, then measures it on pairs it did +not see: how often it scores the preferred answer above the other one, and by +how much on average. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Write the training config | `swaleio/bash` | `cpu-4` | +| Train the reward model | `swaleio/trl-reward` | `a100-1` | +| Score the held-out pairs | `swaleio/transformers` | `a100-1` | +| Upload the reward model, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +Every step is its own task. The scoring step is a short Python script inside the +workflow, run by the `transformers` task. + +The result can drive `swaleio/trl-grpo` or `swaleio/trl-rloo` through +`reward_model_name_or_path`. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `model` | `Qwen/Qwen2.5-0.5B-Instruct` | Model the reward model starts from; all of its weights are trained. | +| `train_split` | `train_prefs[:20000]` | Pairs of `HuggingFaceH4/ultrafeedback_binarized` to train on. | +| `eval_pairs` | `1000` | Held-out pairs, from its `test_prefs` split. | +| `hub_repo` | empty | Hub model repo to upload the reward model to. | + +Training and the upload read the secret `hf_token`. + +## Output + +The reward model in `reward-model/` on the workspace, each held-out pair's two +rewards in `reward-scores.jsonl`, and the accuracy and mean margin in +`reward-metrics.json`. + +## Licenses of the defaults + +- Model: [Qwen/Qwen2.5-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct), Apache-2.0. +- Dataset: [HuggingFaceH4/ultrafeedback_binarized](https://huggingface.co/datasets/HuggingFaceH4/ultrafeedback_binarized), MIT. diff --git a/workflows/reward-model/workflow.yaml b/workflows/reward-model/workflow.yaml new file mode 100644 index 0000000..5f19dbf --- /dev/null +++ b/workflows/reward-model/workflow.yaml @@ -0,0 +1,110 @@ +name: Train a reward model +description: Trains a reward model on preference pairs with TRL, then measures how often it scores the preferred answer higher on held-out pairs. +compute_type: cpu-4 + +inputs: + model: + description: Hub repo id of the model the reward model starts from. All of its weights are trained. + default: Qwen/Qwen2.5-0.5B-Instruct + train_split: + description: Preference pairs to train on, from HuggingFaceH4/ultrafeedback_binarized. + default: train_prefs[:20000] + eval_pairs: + description: Number of held-out pairs to score. + default: "1000" + hub_repo: + description: Hub model repo to upload the reward model to, as namespace/name. Leave empty to keep it on the workspace only. + default: "" + +entry_point: main + +blocks: + main: + tasks: + write_config: + name: Write training config + uses: swaleio/bash + args: + script: | + cat > "$WORKFLOW_STORAGE/reward.yaml" < r["rejected"] for r in rows) + metrics = {"pairs": len(rows), "accuracy": round(correct / len(rows), 4), + "mean_margin": round(sum(r["chosen"] - r["rejected"] for r in rows) / len(rows), 4)} + with open(f"{storage}/reward-scores.jsonl", "w") as f: + f.writelines(json.dumps(r) + "\n" for r in rows) + with open(f"{storage}/reward-metrics.json", "w") as f: + json.dump(metrics, f, indent=2) + print(json.dumps(metrics)) + + publish: + name: Upload when asked + start_on: + - score + if: + condition: ${{inputs.hub_repo}} + true: upload + + upload: + tasks: + upload_model: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + source: ${{env.WORKFLOW_STORAGE}}/reward-model + token: ${{secrets.hf_token}} diff --git a/workflows/rloo-math/README.md b/workflows/rloo-math/README.md new file mode 100644 index 0000000..a404f62 --- /dev/null +++ b/workflows/rloo-math/README.md @@ -0,0 +1,39 @@ +# Train maths reasoning with RLOO + +Trains a model to solve maths word problems with REINFORCE leave-one-out. 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 +base model and the trained model are both scored on GSM8K's test split. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Turn GSM8K questions into chat prompts and reference solutions | `swaleio/duckdb` | `cpu-4` | +| Write the training config | `swaleio/bash` | `cpu-4` | +| Train | `swaleio/trl-rloo` | `a100-1` | +| Evaluate the base model, and the trained model | `swaleio/lm-eval` | `a100-1` each | +| Compare the two scores | `swaleio/duckdb` | `cpu-4` | +| Upload the trained model, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +Every step is its own task. The base model is scored while the other model +trains. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `model` | `Qwen/Qwen2.5-0.5B-Instruct` | Chat model to train; all of its weights are trained. | +| `train_questions` | `2000` | GSM8K training questions to train on. | +| `hub_repo` | empty | Hub model repo to upload the trained model to. | + +Training, the base model's evaluation and the upload read the secret +`hf_token`. + +## Output + +The trained model in `trained/` on the workspace, the scores in `eval-base/` +and `eval-trained/`, and the comparison in the last task's log. + +## Licenses of the defaults + +- Model: [Qwen/Qwen2.5-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct), Apache-2.0. +- Dataset: [openai/gsm8k](https://huggingface.co/datasets/openai/gsm8k), MIT. diff --git a/workflows/rloo-math/workflow.yaml b/workflows/rloo-math/workflow.yaml new file mode 100644 index 0000000..e9f222c --- /dev/null +++ b/workflows/rloo-math/workflow.yaml @@ -0,0 +1,124 @@ +name: Train maths reasoning with RLOO +description: Trains a model on maths word problems with TRL's RLOO, rewarding answers that match the reference, and compares its GSM8K score before and after. +compute_type: cpu-4 + +inputs: + model: + description: Hub repo id of the chat model to train. All of its weights are trained. + default: Qwen/Qwen2.5-0.5B-Instruct + train_questions: + description: Number of GSM8K training questions to train on. + default: "2000" + hub_repo: + description: Hub model repo to upload the trained model to, as namespace/name. Leave empty to keep it on the workspace only. + default: "" + +entry_point: main + +blocks: + main: + tasks: + prepare: + name: Prepare prompts and solutions + uses: swaleio/duckdb + args: + sql: | + -- RLOO reads a prompt column of chat messages; accuracy_reward compares each + -- answer with the solution column, the number after #### in GSM8K's answers. + COPY ( + SELECT [{'role': 'user', 'content': question || '\nPut the final answer in \boxed{}.'}] AS prompt, + trim(split_part(answer, '####', 2)) AS solution + FROM 'hf://datasets/openai/gsm8k/main/train-*.parquet' + LIMIT ${{inputs.train_questions}} + ) TO '${{env.WORKFLOW_STORAGE}}/rloo-train.parquet' (FORMAT parquet); + SELECT count(*) AS questions FROM '${{env.WORKFLOW_STORAGE}}/rloo-train.parquet'; + + write_config: + name: Write training config + uses: swaleio/bash + args: + script: | + cat > "$WORKFLOW_STORAGE/rloo.yaml" <>'$."exact_match,strict-match"')::DOUBLE, 4) AS strict_match, + round((results.gsm8k->>'$."exact_match,flexible-extract"')::DOUBLE, 4) AS flexible_extract + FROM read_json(['${{env.WORKFLOW_STORAGE}}/eval-base/*/results_*.json', + '${{env.WORKFLOW_STORAGE}}/eval-trained/*/results_*.json'], + filename = true, columns = {'results': 'STRUCT(gsm8k JSON)'}) + ORDER BY model; + + publish: + name: Upload when asked + start_on: + - compare + if: + condition: ${{inputs.hub_repo}} + true: upload + + upload: + tasks: + upload_model: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + source: ${{env.WORKFLOW_STORAGE}}/trained + token: ${{secrets.hf_token}} diff --git a/workflows/scans-to-text/README.md b/workflows/scans-to-text/README.md new file mode 100644 index 0000000..b13fade --- /dev/null +++ b/workflows/scans-to-text/README.md @@ -0,0 +1,37 @@ +# Scanned images to text + +Reads the text of scanned pages with Tesseract OCR. Each scan is fetched and +read in its own tasks, all at the same time: once as plain text, and once as a +table of words with Tesseract's confidence in each. A last step gathers the +text and each scan's mean word confidence into one Parquet file, so the scans +Tesseract struggled with stand out. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Make the output folders | `swaleio/bash` | `cpu-4` | +| For each scan: fetch it | `swaleio/http-request` | `cpu-4` | +| For each scan: read its text, and its words with confidences, in parallel | `swaleio/tesseract` | `cpu-4` each | +| Gather text and confidences into `scans.parquet` | `swaleio/duckdb` | `cpu-4` | +| Upload to the Hub, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +Every step is its own task. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `image_urls` | two sample scans from Tesseract's test data | The scans, as a JSON array of URLs. | +| `language` | `eng+deu+fra` | Tesseract language codes, joined with `+`. | +| `hub_repo` | empty | Hub dataset repo to upload the dataset to, as `data/train.parquet`. | + +The upload reads the secret `hf_token`. + +## Output + +`scans.parquet` on the workspace, with `url`, `text` and +`mean_word_confidence` (0 to 100) for each scan, and Tesseract's `.txt` and +`.tsv` files in `text/`. + +## Licenses of the defaults + +- Scans: from [tesseract-ocr/test](https://github.com/tesseract-ocr/test), Apache-2.0. diff --git a/workflows/scans-to-text/workflow.yaml b/workflows/scans-to-text/workflow.yaml new file mode 100644 index 0000000..23f882e --- /dev/null +++ b/workflows/scans-to-text/workflow.yaml @@ -0,0 +1,108 @@ +name: Scanned images to text +description: Reads the text of a list of scanned page images with Tesseract, one task per image, and collects the text and word confidences into one Parquet dataset. +compute_type: cpu-4 + +inputs: + image_urls: + description: The scans to read, as a JSON array of URLs. + default: '["https://raw.githubusercontent.com/tesseract-ocr/test/232ff181c66516116ec0e84c4963f70de15050fd/testing/phototest.tif", "https://raw.githubusercontent.com/tesseract-ocr/test/232ff181c66516116ec0e84c4963f70de15050fd/testing/eurotext.tif"]' + language: + description: Tesseract language code, or several joined with +. + default: eng+deu+fra + hub_repo: + description: Hub dataset repo to upload the dataset to, as namespace/name. Leave empty to keep it on the workspace only. + default: "" + +entry_point: main + +blocks: + main: + tasks: + make_dirs: + name: Make output folders + uses: swaleio/bash + args: + script: mkdir -p "$WORKFLOW_STORAGE/scans" "$WORKFLOW_STORAGE/text" + + each_scan: + name: Read each scan + start_on: + - make_dirs + for_each: + items: ${{inputs.image_urls}} + block: read_one + + collect: + name: Collect into a dataset + uses: swaleio/duckdb + start_on: + - each_scan + args: + sql: | + CREATE TABLE urls AS + SELECT unnest(from_json($$${{inputs.image_urls}}$$, '["VARCHAR"]')) AS url, + generate_subscripts(from_json($$${{inputs.image_urls}}$$, '["VARCHAR"]'), 1) - 1 AS item; + -- Tesseract's TSV has one row per word, with its confidence from 0 to 100. + CREATE TABLE words AS + SELECT regexp_extract(filename, '(\d+)\.tsv$', 1)::INT AS item, conf, text + FROM read_csv('${{env.WORKFLOW_STORAGE}}/text/*.tsv', delim = '\t', quote = '', header = true, + filename = true, ignore_errors = true) + WHERE conf >= 0; + CREATE TABLE scans AS + SELECT u.url, t.content AS text, + (SELECT round(avg(conf), 1) FROM words w WHERE w.item = u.item) AS mean_word_confidence + FROM urls u + JOIN read_text('${{env.WORKFLOW_STORAGE}}/text/*.txt') t + ON regexp_extract(t.filename, '(\d+)\.txt$', 1)::INT = u.item + ORDER BY u.item; + SELECT url, length(text) AS characters, mean_word_confidence FROM scans; + COPY scans TO '${{env.WORKFLOW_STORAGE}}/scans.parquet' (FORMAT parquet); + + publish: + name: Upload when asked + start_on: + - collect + if: + condition: ${{inputs.hub_repo}} + true: upload + + read_one: + tasks: + fetch: + name: Fetch scan + uses: swaleio/http-request + args: + url: ${{tasks.each_scan.for_each.item}} + expected_status: "200" + response_path: ${{env.WORKFLOW_STORAGE}}/scans/${{tasks.each_scan.for_each.index}} + read_text: + name: Read text + uses: swaleio/tesseract + start_on: + - fetch + args: + image: ${{env.WORKFLOW_STORAGE}}/scans/${{tasks.each_scan.for_each.index}} + output_base: ${{env.WORKFLOW_STORAGE}}/text/${{tasks.each_scan.for_each.index}} + language: ${{inputs.language}} + read_words: + name: Read words with confidences + uses: swaleio/tesseract + start_on: + - fetch + args: + image: ${{env.WORKFLOW_STORAGE}}/scans/${{tasks.each_scan.for_each.index}} + output_base: ${{env.WORKFLOW_STORAGE}}/text/${{tasks.each_scan.for_each.index}} + language: ${{inputs.language}} + format: tsv + + upload: + tasks: + upload_dataset: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + repo_type: dataset + source: ${{env.WORKFLOW_STORAGE}}/scans.parquet + path_in_repo: data/train.parquet + token: ${{secrets.hf_token}} diff --git a/workflows/score-gguf/README.md b/workflows/score-gguf/README.md new file mode 100644 index 0000000..14393c0 --- /dev/null +++ b/workflows/score-gguf/README.md @@ -0,0 +1,49 @@ +# Score a GGUF model on a CPU + +Measures how well a quantized model answers, and how fast, in the exact GGUF +file you would ship. llama.cpp serves the model on a CPU compute type, several +client tasks answer GSM8K maths questions through that one server at the same +time, and the last step checks each answer against the reference and reports +the accuracy and the tokens per second. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Fetch the GGUF file | `swaleio/hf-download` | `cpu-4` | +| Split the questions into shards | `swaleio/duckdb` | `cpu-4` | +| Serve the model, as a runner | `swaleio/llamacpp-server` | `cpu-16` | +| Wait for the server, checking every 5 seconds | `swaleio/http-request` | `cpu-4` | +| Answer each shard, one client task per shard, all at once | `swaleio/python-3-13` | `cpu-4` each | +| Check the answers and report accuracy and speed | `swaleio/duckdb` | `cpu-4` | + +Every step is its own task. The server answers 4 requests at once, so the +default 4 shards keep it busy; when they are done, the platform stops it. Each +client is a short Python script inside the workflow that uses only the standard +library. The server needs no GPU; give it `a100-1` instead and llama.cpp +offloads the model to the GPU. + +The model is asked to reason step by step and put its final answer within +`\boxed{}`, the form Qwen's models are trained to answer maths in. The score +takes the number in its last `\boxed{}`, or the last number in its reply when +it has none, and the report also says how often it boxed its answer. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `repo` | `Qwen/Qwen2.5-1.5B-Instruct-GGUF` | Hub repo holding the GGUF file. | +| `file` | `qwen2.5-1.5b-instruct-q4_k_m.gguf` | The file to score. | +| `questions` | `200` | Questions from GSM8K's test split to answer. | +| `shards` | `["0", "1", "2", "3"]` | One client task per element. | + +The download reads the secret `hf_token`. + +## Output + +`scored.parquet` on the workspace, with each question, the reference answer, +the model's reply, the number taken from it and whether it is correct, and the +summary in the last task's log. + +## Licenses of the defaults + +- Model: [Qwen/Qwen2.5-1.5B-Instruct-GGUF](https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF), Apache-2.0. +- Dataset: [openai/gsm8k](https://huggingface.co/datasets/openai/gsm8k), MIT. diff --git a/workflows/score-gguf/workflow.yaml b/workflows/score-gguf/workflow.yaml new file mode 100644 index 0000000..6ff0118 --- /dev/null +++ b/workflows/score-gguf/workflow.yaml @@ -0,0 +1,140 @@ +name: Score a GGUF model on a CPU +description: Serves a quantized GGUF model with llama.cpp on a CPU, has several client tasks answer GSM8K maths questions through it in parallel, one per shard, and reports the model's accuracy and speed. +compute_type: cpu-4 + +inputs: + repo: + description: Hub repo id holding the GGUF file. + default: Qwen/Qwen2.5-1.5B-Instruct-GGUF + file: + description: The GGUF file to score. + default: qwen2.5-1.5b-instruct-q4_k_m.gguf + questions: + description: Number of questions from GSM8K's test split to answer. + default: "200" + shards: + description: The client shards, as a JSON array; one client task runs per element and answers every nth question. The server answers 4 requests at once, so more than 4 shards only queue. + default: '["0", "1", "2", "3"]' + +entry_point: main + +blocks: + main: + tasks: + fetch: + name: Fetch the GGUF file + uses: swaleio/hf-download + args: + repo: ${{inputs.repo}} + include: ${{inputs.file}} + dest: ${{env.WORKFLOW_STORAGE}}/gguf + token: ${{secrets.hf_token}} + + split: + name: Split the questions into shards + uses: swaleio/duckdb + args: + sql: | + -- The reference answer is the number after #### in GSM8K's worked answers. + CREATE TABLE questions AS + SELECT row_number() OVER () - 1 AS id, question, + replace(trim(split_part(answer, '####', 2)), ',', '') AS reference + FROM 'hf://datasets/openai/gsm8k/main/test-*.parquet' + LIMIT ${{inputs.questions}}; + CREATE TABLE sharded AS + SELECT id, question, id % json_array_length($$${{inputs.shards}}$$) AS shard FROM questions; + COPY sharded TO '${{env.WORKFLOW_STORAGE}}/shards' (FORMAT json, PARTITION_BY (shard), OVERWRITE_OR_IGNORE); + COPY questions TO '${{env.WORKFLOW_STORAGE}}/questions.parquet' (FORMAT parquet); + SELECT shard, count(*) AS questions FROM sharded GROUP BY shard ORDER BY shard; + + serve: + name: Serve the model + uses: swaleio/llamacpp-server + compute_type: cpu-16 + start_on: + - fetch + terminate_on: + - each_shard + args: + model: ${{env.WORKFLOW_STORAGE}}/gguf/${{inputs.file}} + ctx_size: "8192" + + wait_ready: + name: Wait for the server + uses: swaleio/http-request + start_on: + - serve + args: + url: http://${{tasks.serve.ip-address}}:9931/health + retry: "360" + retry_delay: "5" + expected_status: "200" + + each_shard: + name: Answer each shard + start_on: + - wait_ready + - split + for_each: + items: ${{inputs.shards}} + block: answer_shard + + score: + name: Score the answers + uses: swaleio/duckdb + start_on: + - each_shard + args: + sql: | + -- The model's answer is the number in its last \boxed{}, or else the last number + -- in its reply. + CREATE TABLE scored AS + SELECT q.id, q.question, q.reference, a.reply, a.completion_tokens, a.started, a.finished, + regexp_extract_all(a.reply, '\\boxed\{([^}]*)\}', 1)[-1] AS boxed, + replace(coalesce(nullif(regexp_extract(boxed, '-?[0-9][0-9,]*(\.[0-9]+)?'), ''), + regexp_extract_all(a.reply, '-?[0-9][0-9,]*(\.[0-9]+)?')[-1]), ',', '') AS predicted, + coalesce(TRY_CAST(predicted AS DOUBLE) = TRY_CAST(q.reference AS DOUBLE), false) AS correct + FROM '${{env.WORKFLOW_STORAGE}}/questions.parquet' q + JOIN read_json('${{env.WORKFLOW_STORAGE}}/answers/*.jsonl') a USING (id) + ORDER BY q.id; + COPY scored TO '${{env.WORKFLOW_STORAGE}}/scored.parquet' (FORMAT parquet); + SELECT count(*) AS questions, + round(100.0 * avg(correct::INT), 1) AS accuracy_percent, + round(100.0 * avg((boxed IS NOT NULL)::INT), 1) AS boxed_percent, + sum(completion_tokens) AS tokens, + round(max(finished) - min(started)) AS seconds, + round(sum(completion_tokens) / (max(finished) - min(started)), 1) AS tokens_per_second + FROM scored; + + answer_shard: + tasks: + answer: + name: Answer the shard + uses: swaleio/python-3-13 + args: + script: | + import glob, json, os, time, urllib.request + + storage = os.environ["WORKFLOW_STORAGE"] + shard = "${{tasks.each_shard.for_each.item}}" + server = "http://${{tasks.serve.ip-address}}:9931/v1/chat/completions" + os.makedirs(f"{storage}/answers", exist_ok=True) + rows = [] + for path in glob.glob(f"{storage}/shards/shard={shard}/*.json"): + with open(path) as f: + rows += [json.loads(line) for line in f if line.strip()] + + with open(f"{storage}/answers/{shard}.jsonl", "w") as out: + for row in rows: + prompt = row["question"] + "\nPlease reason step by step, and put your final answer within \\boxed{}." + body = json.dumps({"messages": [{"role": "user", "content": prompt}], + "max_tokens": 512, "temperature": 0}).encode() + request = urllib.request.Request(server, body, {"Content-Type": "application/json"}) + started = time.time() + with urllib.request.urlopen(request, timeout=600) as response: + answer = json.load(response) + out.write(json.dumps({"id": row["id"], + "reply": answer["choices"][0]["message"]["content"], + "completion_tokens": answer["usage"]["completion_tokens"], + "started": started, "finished": time.time()}) + "\n") + print(f"shard {shard}: answered {len(rows)} questions") diff --git a/workflows/semantic-dedup/README.md b/workflows/semantic-dedup/README.md new file mode 100644 index 0000000..290ce19 --- /dev/null +++ b/workflows/semantic-dedup/README.md @@ -0,0 +1,47 @@ +# Semantic deduplication + +Removes rows that say nearly the same thing in different words, which exact +deduplication misses. vLLM embeds every row, a short NumPy script compares +every row with every other and groups the pairs above a similarity threshold, +and DuckDB keeps one row of each group and shows the closest pairs it judged +different, so the threshold can be checked. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Fetch this repository's scripts at `examples_ref` | `swaleio/git-clone` | `cpu-4` | +| Fetch the embedding model | `swaleio/hf-download` | `cpu-4` | +| Number the rows, write one embedding request per row, cutting a text longer than the model takes, count exact duplicates | `swaleio/duckdb` | `cpu-4` | +| Embed | `swaleio/vllm-batch` | `a100-1` | +| Collect the vectors and count failed requests; a row whose request failed is kept | `swaleio/duckdb` | `cpu-4` | +| Find near-duplicate pairs and the rows to drop ([`similar_pairs.py`](similar_pairs.py)) | `swaleio/python-3-13` | `cpu-4` | +| Show sample pairs, write the dataset without the dropped rows | `swaleio/duckdb` | `cpu-4` | +| Upload to the Hub, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +**What stays one script:** the similarity step. Comparing every row with every +other is one matrix product per block of rows, and grouping the pairs needs all +of them at once. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `model` | `BAAI/bge-small-en-v1.5` | Embedding model vLLM serves. | +| `dataset` | the `train_prefs` split of `HuggingFaceH4/ultrafeedback_binarized` | Parquet file or glob, as a DuckDB path. | +| `text_column` | `prompt` | Column compared. | +| `limit` | `20000` | Rows to deduplicate. | +| `threshold` | `0.95` | Cosine similarity from which two rows are near-duplicates. | +| `examples_ref` | `main` | Branch, tag or full commit SHA of this repository whose scripts run. | +| `hub_repo` | empty | Hub dataset repo to upload the result to, as `data/train.parquet`. | + +The download and the upload read the secret `hf_token`. + +## Output + +`deduplicated.parquet` on the workspace, the similar pairs in `pairs.parquet` +and the dropped row ids in `drop.parquet`. + +## Licenses + +- Model: [BAAI/bge-small-en-v1.5](https://huggingface.co/BAAI/bge-small-en-v1.5), MIT. +- Dataset: [HuggingFaceH4/ultrafeedback_binarized](https://huggingface.co/datasets/HuggingFaceH4/ultrafeedback_binarized), MIT. +- Packages the similarity step installs: NumPy (BSD-3-Clause) and PyArrow (Apache-2.0). diff --git a/workflows/semantic-dedup/similar_pairs.py b/workflows/semantic-dedup/similar_pairs.py new file mode 100644 index 0000000..6efb75d --- /dev/null +++ b/workflows/semantic-dedup/similar_pairs.py @@ -0,0 +1,60 @@ +"""Finds pairs of rows whose embeddings are nearly the same, on a CPU, with NumPy. + +Compares every row with every other in blocks, so memory stays bounded, and +writes each pair above --threshold cosine similarity. Then keeps the first row +of each group of near-duplicates and lists the others to drop. This is the +step of the workflow that stays a single script: the all-pairs comparison is +one matrix product per block. +""" + +import argparse + +import numpy as np +import pyarrow as pa +import pyarrow.parquet as pq + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--embeddings", required=True, help="Parquet file with id and embedding columns") + p.add_argument("--threshold", type=float, default=0.95) + p.add_argument("--pairs", required=True, help="Parquet file the similar pairs are written to") + p.add_argument("--drop", required=True, help="Parquet file the ids to drop are written to") + p.add_argument("--block", type=int, default=2048) + args = p.parse_args() + + table = pq.read_table(args.embeddings) + ids = np.array(table.column("id").to_pylist()) + vectors = np.array(table.column("embedding").to_pylist(), dtype=np.float32) + vectors /= np.linalg.norm(vectors, axis=1, keepdims=True) + + left, right, scores = [], [], [] + for start in range(0, len(vectors), args.block): + similarity = vectors[start:start + args.block] @ vectors.T + rows, columns = np.nonzero(similarity >= args.threshold) + keep = columns > rows + start + left += ids[rows[keep] + start].tolist() + right += ids[columns[keep]].tolist() + scores += similarity[rows[keep], columns[keep]].round(4).tolist() + pq.write_table(pa.table({"left_id": left, "right_id": right, "similarity": scores}), args.pairs) + + # Union-find over the pairs: every group keeps its smallest id. + parent = {} + + def root(x): + while parent.get(x, x) != x: + parent[x] = parent.get(parent[x], parent[x]) + x = parent[x] + return x + + for a, b in zip(left, right): + ra, rb = root(a), root(b) + if ra != rb: + parent[max(ra, rb)] = min(ra, rb) + drop = sorted(x for x in set(left) | set(right) if root(x) != x) + pq.write_table(pa.table({"id": drop}), args.drop) + print(f"{len(ids)} rows, {len(left)} similar pairs, {len(drop)} rows to drop") + + +if __name__ == "__main__": + main() diff --git a/workflows/semantic-dedup/workflow.yaml b/workflows/semantic-dedup/workflow.yaml new file mode 100644 index 0000000..31c47cf --- /dev/null +++ b/workflows/semantic-dedup/workflow.yaml @@ -0,0 +1,149 @@ +name: Semantic deduplication +description: Embeds every row of a dataset with vLLM batch inference, finds pairs of rows that mean nearly the same, and writes the dataset without the near-duplicates. +compute_type: cpu-4 + +inputs: + model: + description: Hub repo id of an embedding model vLLM serves. + default: BAAI/bge-small-en-v1.5 + dataset: + description: Parquet file or glob, as a DuckDB path. + default: hf://datasets/HuggingFaceH4/ultrafeedback_binarized/data/train_prefs-*.parquet + text_column: + description: Column whose meaning is compared. + default: prompt + limit: + description: Rows to deduplicate. + default: "20000" + threshold: + description: Cosine similarity from which two rows count as near-duplicates. + default: "0.95" + examples_ref: + description: Branch, tag or full commit SHA of swaleio/examples whose scripts run. + default: main + hub_repo: + description: Hub dataset repo to upload the deduplicated dataset 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}}/model + token: ${{secrets.hf_token}} + + requests: + name: Write embedding requests + uses: swaleio/duckdb + args: + sql: | + CREATE TABLE rows AS + SELECT row_number() OVER () - 1 AS id, * + FROM (SELECT * FROM '${{inputs.dataset}}' LIMIT ${{inputs.limit}}); + COPY rows TO '${{env.WORKFLOW_STORAGE}}/rows.parquet' (FORMAT parquet); + COPY (SELECT id::VARCHAR AS custom_id, 'POST' AS method, '/v1/embeddings' AS url, + {'model': '${{env.WORKFLOW_STORAGE}}/model', 'input': "${{inputs.text_column}}", + 'truncate_prompt_tokens': -1} AS body + FROM rows) + TO '${{env.WORKFLOW_STORAGE}}/requests.jsonl' (FORMAT json); + SELECT count(*) AS rows, count(DISTINCT "${{inputs.text_column}}") AS exactly_distinct FROM rows; + + embed: + name: Embed + uses: swaleio/vllm-batch + compute_type: a100-1 + start_on: + - fetch_model + - requests + args: + model: ${{env.WORKFLOW_STORAGE}}/model + input_file: ${{env.WORKFLOW_STORAGE}}/requests.jsonl + output_file: ${{env.WORKFLOW_STORAGE}}/embeddings.jsonl + + collect: + name: Collect vectors + uses: swaleio/duckdb + start_on: + - embed + args: + sql: | + CREATE TABLE responses AS SELECT * FROM read_json('${{env.WORKFLOW_STORAGE}}/embeddings.jsonl'); + COPY (SELECT custom_id::BIGINT AS id, response.body.data[1].embedding::FLOAT[] AS embedding + FROM responses WHERE response.status_code = 200) + TO '${{env.WORKFLOW_STORAGE}}/vectors.parquet' (FORMAT parquet); + SELECT count(*) FILTER (WHERE response.status_code = 200) AS vectors, + count(*) FILTER (WHERE response.status_code IS DISTINCT FROM 200) AS failed, + len(any_value(response.body.data[1].embedding)) AS dimensions + FROM responses; + + find_pairs: + name: Find near-duplicate pairs + uses: swaleio/python-3-13 + start_on: + - fetch_scripts + - collect + 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-numpy.txt"], check=True) + subprocess.run([sys.executable, f"{examples}/workflows/semantic-dedup/similar_pairs.py", + "--embeddings", f"{storage}/vectors.parquet", "--threshold", "${{inputs.threshold}}", + "--pairs", f"{storage}/pairs.parquet", "--drop", f"{storage}/drop.parquet"], + env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True) + + drop_rows: + name: Drop the near-duplicates + uses: swaleio/duckdb + start_on: + - find_pairs + args: + sql: | + SELECT p.similarity, left(a."${{inputs.text_column}}", 70) AS kept, left(b."${{inputs.text_column}}", 70) AS dropped + FROM '${{env.WORKFLOW_STORAGE}}/pairs.parquet' p + JOIN '${{env.WORKFLOW_STORAGE}}/rows.parquet' a ON a.id = p.left_id + JOIN '${{env.WORKFLOW_STORAGE}}/rows.parquet' b ON b.id = p.right_id + WHERE a."${{inputs.text_column}}" <> b."${{inputs.text_column}}" + ORDER BY p.similarity LIMIT 10; + COPY (SELECT * EXCLUDE (id) FROM '${{env.WORKFLOW_STORAGE}}/rows.parquet' + WHERE id NOT IN (SELECT id FROM '${{env.WORKFLOW_STORAGE}}/drop.parquet') ORDER BY id) + TO '${{env.WORKFLOW_STORAGE}}/deduplicated.parquet' (FORMAT parquet); + SELECT (SELECT count(*) FROM '${{env.WORKFLOW_STORAGE}}/rows.parquet') AS rows_before, + (SELECT count(*) FROM '${{env.WORKFLOW_STORAGE}}/deduplicated.parquet') AS rows_after; + + publish: + name: Upload when asked + start_on: + - drop_rows + if: + condition: ${{inputs.hub_repo}} + true: upload + + upload: + tasks: + upload_dataset: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + repo_type: dataset + source: ${{env.WORKFLOW_STORAGE}}/deduplicated.parquet + path_in_repo: data/train.parquet + token: ${{secrets.hf_token}} diff --git a/workflows/sentence-embeddings/README.md b/workflows/sentence-embeddings/README.md new file mode 100644 index 0000000..e51f21f --- /dev/null +++ b/workflows/sentence-embeddings/README.md @@ -0,0 +1,50 @@ +# Sentence embeddings for retrieval + +Fine-tunes a sentence-embedding model with Sentence Transformers so that a +question lands close to the text that answers it, then checks that retrieval +got better: the base model and the fine-tuned model each embed the same +held-out questions and answers, and SQL ranks every answer for every question +and reports recall at 1 and 10 and the mean reciprocal rank for both. + +| 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` | +| Build the train and eval pairs | `swaleio/duckdb` | `cpu-4` | +| Train with multiple-negatives ranking loss ([`train.py`](train.py)) | `swaleio/transformers` | `a100-1` | +| Embed the eval pairs with the base model, and with the fine-tuned model ([`embed.py`](embed.py)) | `swaleio/transformers` | `a100-1` each | +| Rank and compare retrieval | `swaleio/duckdb` | `cpu-4` | +| Upload the model, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +The base model embeds the eval pairs while the other one trains. + +**What stays one script:** the training loop, which holds the model, the +optimizer and the batches together on one GPU. With multiple-negatives ranking +loss each batch's other pairs are its negatives, so the batch cannot be split +either. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `model` | `sentence-transformers/all-MiniLM-L6-v2` | Sentence-embedding model to fine-tune. | +| `train_data`, `eval_data` | the train and test splits of `openai/gsm8k` | Parquet files or globs, as DuckDB paths. | +| `anchor_column` | `question` | Column holding the query side of each pair. | +| `positive_column` | `answer` | Column holding the text that answers it. | +| `epochs` | `1` | Training epochs. | +| `examples_ref` | `main` | Branch, tag or full commit SHA of this repository whose scripts run. | +| `hub_repo` | empty | Hub 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, both models' vectors in +`vectors-base.parquet` and `vectors-tuned.parquet`, and the comparison in the +last task's log. + +## Licenses + +- Model: [sentence-transformers/all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2), Apache-2.0. +- Dataset: [openai/gsm8k](https://huggingface.co/datasets/openai/gsm8k), MIT. +- Packages the GPU steps install: Sentence Transformers (Apache-2.0), scikit-learn, SciPy, joblib, threadpoolctl and cloudpickle (BSD-3-Clause) and narwhals (MIT). diff --git a/workflows/sentence-embeddings/embed.py b/workflows/sentence-embeddings/embed.py new file mode 100644 index 0000000..7f11ee8 --- /dev/null +++ b/workflows/sentence-embeddings/embed.py @@ -0,0 +1,35 @@ +"""Embeds the eval queries and their corpus with a sentence-embedding model, on a GPU. + +Writes one Parquet file per model with each text's role, id and vector, so the +retrieval metrics can be computed in SQL without a GPU. +""" + +import argparse + +import pyarrow as pa +import pyarrow.parquet as pq +from sentence_transformers import SentenceTransformer + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Hub repo id or directory of the model") + p.add_argument("--pairs", required=True, help="Parquet file with id, anchor and positive columns") + p.add_argument("--output", required=True, help="Parquet file the vectors are written to") + args = p.parse_args() + + model = SentenceTransformer(args.model, device="cuda") + pairs = pq.read_table(args.pairs).to_pydict() + queries = model.encode(pairs["anchor"], batch_size=128, normalize_embeddings=True).tolist() + corpus = model.encode(pairs["positive"], batch_size=128, normalize_embeddings=True).tolist() + count = len(pairs["id"]) + pq.write_table(pa.table({ + "role": ["query"] * count + ["document"] * count, + "id": pairs["id"] * 2, + "embedding": queries + corpus, + }), args.output) + print(f"embedded {count} queries and {count} documents") + + +if __name__ == "__main__": + main() diff --git a/workflows/sentence-embeddings/train.py b/workflows/sentence-embeddings/train.py new file mode 100644 index 0000000..198e580 --- /dev/null +++ b/workflows/sentence-embeddings/train.py @@ -0,0 +1,47 @@ +"""Fine-tunes a sentence-embedding model on (anchor, positive) pairs, on a GPU. + +Uses multiple-negatives ranking loss: within a batch, every other pair's +positive is a negative, so plain pairs are enough. The training loop is the one +step of the workflow that stays a single script. +""" + +import argparse + +from datasets import load_dataset +from sentence_transformers import SentenceTransformer, SentenceTransformerTrainer, SentenceTransformerTrainingArguments +from sentence_transformers.losses import MultipleNegativesRankingLoss + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Hub repo id or directory of the model to fine-tune") + p.add_argument("--pairs", required=True, help="Parquet file with anchor and positive columns") + p.add_argument("--output", required=True, help="Directory the fine-tuned model is saved to") + p.add_argument("--epochs", type=float, default=1) + p.add_argument("--batch-size", type=int, default=64) + args = p.parse_args() + + model = SentenceTransformer(args.model) + pairs = load_dataset("parquet", data_files=args.pairs, split="train") + trainer = SentenceTransformerTrainer( + model=model, + args=SentenceTransformerTrainingArguments( + output_dir=f"{args.output}-checkpoints", + num_train_epochs=args.epochs, + per_device_train_batch_size=args.batch_size, + learning_rate=2e-5, + bf16=True, + # Two copies of one text in a batch would count as a negative of itself. + batch_sampler="no_duplicates", + save_strategy="no", + report_to="none", + ), + train_dataset=pairs, + loss=MultipleNegativesRankingLoss(model), + ) + trainer.train() + model.save(args.output) + + +if __name__ == "__main__": + main() diff --git a/workflows/sentence-embeddings/workflow.yaml b/workflows/sentence-embeddings/workflow.yaml new file mode 100644 index 0000000..1685e30 --- /dev/null +++ b/workflows/sentence-embeddings/workflow.yaml @@ -0,0 +1,170 @@ +name: Sentence embeddings for retrieval +description: Fine-tunes a sentence-embedding model on question and answer pairs, embeds held-out pairs with the base and the fine-tuned model, and compares their retrieval recall and MRR in SQL. +compute_type: cpu-4 + +inputs: + model: + description: Hub repo id of the sentence-embedding model to fine-tune. + default: sentence-transformers/all-MiniLM-L6-v2 + train_data: + description: Parquet file or glob of training pairs, as a DuckDB path. + default: hf://datasets/openai/gsm8k/main/train-*.parquet + eval_data: + description: Parquet file or glob of held-out pairs, as a DuckDB path. + default: hf://datasets/openai/gsm8k/main/test-*.parquet + anchor_column: + description: Column holding the query side of each pair. + default: question + positive_column: + description: Column holding the document that answers it. + default: answer + epochs: + description: Training epochs. + default: "1" + examples_ref: + description: Branch, tag or full commit SHA of swaleio/examples whose scripts run. + default: main + hub_repo: + description: Hub 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: Build the pairs + uses: swaleio/duckdb + args: + sql: | + COPY (SELECT DISTINCT "${{inputs.anchor_column}}" AS anchor, "${{inputs.positive_column}}" AS positive + FROM '${{inputs.train_data}}') + TO '${{env.WORKFLOW_STORAGE}}/train-pairs.parquet' (FORMAT parquet); + COPY (SELECT row_number() OVER () AS id, "${{inputs.anchor_column}}" AS anchor, "${{inputs.positive_column}}" AS positive + FROM '${{inputs.eval_data}}') + TO '${{env.WORKFLOW_STORAGE}}/eval-pairs.parquet' (FORMAT parquet); + SELECT (SELECT count(*) FROM '${{env.WORKFLOW_STORAGE}}/train-pairs.parquet') AS train_pairs, + (SELECT count(*) FROM '${{env.WORKFLOW_STORAGE}}/eval-pairs.parquet') AS eval_pairs; + + train: + name: Train + uses: swaleio/transformers + compute_type: a100-1 + 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", "--no-deps", "--target", "/tmp/deps", + "-r", f"{examples}/requirements/gpu-sentence-transformers.txt"], check=True) + subprocess.run([sys.executable, f"{examples}/workflows/sentence-embeddings/train.py", + "--model", f"{storage}/base-model", "--pairs", f"{storage}/train-pairs.parquet", + "--epochs", "${{inputs.epochs}}", "--output", f"{storage}/model"], + env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True) + + embed_base: + name: Embed with the base model + uses: swaleio/transformers + compute_type: a100-1 + 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", "--no-deps", "--target", "/tmp/deps", + "-r", f"{examples}/requirements/gpu-sentence-transformers.txt"], check=True) + subprocess.run([sys.executable, f"{examples}/workflows/sentence-embeddings/embed.py", + "--model", f"{storage}/base-model", "--pairs", f"{storage}/eval-pairs.parquet", + "--output", f"{storage}/vectors-base.parquet"], + env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True) + + embed_tuned: + name: Embed with the fine-tuned model + uses: swaleio/transformers + compute_type: a100-1 + start_on: + - train + 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-sentence-transformers.txt"], check=True) + subprocess.run([sys.executable, f"{examples}/workflows/sentence-embeddings/embed.py", + "--model", f"{storage}/model", "--pairs", f"{storage}/eval-pairs.parquet", + "--output", f"{storage}/vectors-tuned.parquet"], + env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True) + + score: + name: Compare retrieval + uses: swaleio/duckdb + start_on: + - embed_base + - embed_tuned + args: + sql: | + -- Each query's own answer is the one document that counts as relevant. The + -- vectors are normalised, so their dot product is their cosine similarity. + CREATE TABLE vectors AS + SELECT 'base' AS model, * FROM '${{env.WORKFLOW_STORAGE}}/vectors-base.parquet' + UNION ALL + SELECT 'fine-tuned', * FROM '${{env.WORKFLOW_STORAGE}}/vectors-tuned.parquet'; + CREATE TABLE ranks AS + SELECT model, query, rank FROM ( + SELECT q.model, q.id AS query, d.id AS document, + row_number() OVER (PARTITION BY q.model, q.id + ORDER BY list_dot_product(q.embedding, d.embedding) DESC) AS rank + FROM vectors q JOIN vectors d ON q.model = d.model AND q.role = 'query' AND d.role = 'document') + WHERE query = document; + SELECT model, count(*) AS queries, + round(avg((rank = 1)::INT), 4) AS recall_at_1, + round(avg((rank <= 10)::INT), 4) AS recall_at_10, + round(avg(1.0 / rank), 4) AS mrr + FROM ranks GROUP BY model ORDER BY model; + + publish: + name: Upload when asked + start_on: + - score + if: + condition: ${{inputs.hub_repo}} + true: upload + + upload: + tasks: + upload_model: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + source: ${{env.WORKFLOW_STORAGE}}/model + token: ${{secrets.hf_token}} diff --git a/workflows/setfit-classifier/README.md b/workflows/setfit-classifier/README.md new file mode 100644 index 0000000..a034eb1 --- /dev/null +++ b/workflows/setfit-classifier/README.md @@ -0,0 +1,45 @@ +# Few-shot classifier with SetFit + +Trains a text classifier from a few labelled examples per class with SetFit: +it fine-tunes a sentence-embedding model on pairs of the examples, then fits a +classification head on the embeddings. Useful when labelling hundreds of +examples is not an option. The prediction and the scores are separate steps. + +| 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` | +| Draw `per_label` examples of each label, the same ones every run | `swaleio/duckdb` | `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` | +| Upload the classifier, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +**What stays one script:** training. SetFit's two stages, contrastive +fine-tuning of the embedding model and fitting the head, both run inside one +`Trainer.train()` call. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `model` | `sentence-transformers/all-MiniLM-L6-v2` | Sentence-embedding model SetFit starts from. | +| `train_data`, `eval_data` | the train and validation splits of `google-research-datasets/poem_sentiment` | Parquet files or globs, as DuckDB paths. | +| `text_column`, `label_column` | `verse_text`, `label` | Columns holding the text and the label number. | +| `labels` | `negative,positive,no_impact,mixed` | Label names in label-number order. | +| `per_label` | `16` | Training examples per label. | +| `examples_ref` | `main` | Branch, tag or full commit SHA of this repository whose scripts run. | +| `hub_repo` | empty | Hub model repo to upload the classifier to. | + +The download and the upload read the secret `hf_token`. + +## Output + +The classifier in `model/` on the workspace, the predictions in +`predictions.parquet`, and `metrics.json` with accuracy and macro F1. + +## Licenses + +- Model: [sentence-transformers/all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2), Apache-2.0. +- Dataset: [google-research-datasets/poem_sentiment](https://huggingface.co/datasets/google-research-datasets/poem_sentiment), CC BY 4.0. +- Packages the GPU steps install: SetFit, Sentence Transformers and evaluate (Apache-2.0), scikit-learn, SciPy, joblib, threadpoolctl and cloudpickle (BSD-3-Clause) and narwhals (MIT). diff --git a/workflows/setfit-classifier/predict.py b/workflows/setfit-classifier/predict.py new file mode 100644 index 0000000..6ed3181 --- /dev/null +++ b/workflows/setfit-classifier/predict.py @@ -0,0 +1,29 @@ +"""Predicts a label for every eval text with a trained SetFit classifier, on a GPU. + +Writes the true and predicted label numbers to Parquet; scoring them needs no GPU. +""" + +import argparse + +import pyarrow as pa +import pyarrow.parquet as pq +from setfit import SetFitModel + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Directory of the trained classifier") + p.add_argument("--eval", required=True, help="Parquet file with text and label columns") + p.add_argument("--output", required=True, help="Parquet file the predictions are written to") + args = p.parse_args() + + model = SetFitModel.from_pretrained(args.model).to("cuda") + rows = pq.read_table(args.eval).to_pydict() + names = [str(name) for name in model.predict(rows["text"], batch_size=64)] + index = {label: i for i, label in enumerate(model.labels)} + pq.write_table(pa.table({"label": rows["label"], "prediction": [index[n] for n in names]}), args.output) + print(f"predicted {len(names)} texts") + + +if __name__ == "__main__": + main() diff --git a/workflows/setfit-classifier/train.py b/workflows/setfit-classifier/train.py new file mode 100644 index 0000000..5bbea76 --- /dev/null +++ b/workflows/setfit-classifier/train.py @@ -0,0 +1,35 @@ +"""Trains a SetFit few-shot classifier, on a GPU. + +SetFit first fine-tunes a sentence-embedding model on pairs drawn from the few +labelled examples, then fits a classification head on the embeddings. Both +happen inside one SetFit Trainer.train() call, which is why training stays a +single script. +""" + +import argparse + +from datasets import load_dataset +from setfit import SetFitModel, Trainer, TrainingArguments + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Hub repo id or directory of the sentence-embedding model") + p.add_argument("--train", required=True, help="Parquet file with text and label columns") + p.add_argument("--labels", required=True, help="Label names, separated by commas, in label-number order") + p.add_argument("--output", required=True, help="Directory the trained classifier is saved to") + p.add_argument("--epochs", type=int, default=1) + args = p.parse_args() + + model = SetFitModel.from_pretrained(args.model, labels=args.labels.split(",")) + trainer = Trainer( + model=model, + args=TrainingArguments(num_epochs=args.epochs, batch_size=16, report_to="none"), + train_dataset=load_dataset("parquet", data_files=args.train, split="train"), + ) + trainer.train() + model.save_pretrained(args.output) + + +if __name__ == "__main__": + main() diff --git a/workflows/setfit-classifier/workflow.yaml b/workflows/setfit-classifier/workflow.yaml new file mode 100644 index 0000000..9fa7504 --- /dev/null +++ b/workflows/setfit-classifier/workflow.yaml @@ -0,0 +1,154 @@ +name: Few-shot classifier with SetFit +description: Trains a text classifier from a handful of examples per label with SetFit, then predicts the eval split on a GPU and computes accuracy and macro F1 in SQL. +compute_type: cpu-4 + +inputs: + model: + description: Hub repo id of the sentence-embedding model SetFit starts from. + default: sentence-transformers/all-MiniLM-L6-v2 + train_data: + description: Parquet file or glob to draw the few training examples from, as a DuckDB path. + default: hf://datasets/google-research-datasets/poem_sentiment/data/train-00000-of-00001.parquet + eval_data: + description: Parquet file or glob of evaluation rows, as a DuckDB path. + default: hf://datasets/google-research-datasets/poem_sentiment/data/validation-00000-of-00001.parquet + text_column: + description: Column holding the text. + default: verse_text + label_column: + description: Column holding the label, as a number from 0. + default: label + labels: + description: Label names, separated by commas, in label-number order. + default: negative,positive,no_impact,mixed + per_label: + description: Training examples drawn for each label. + default: "16" + examples_ref: + description: Branch, tag or full commit SHA of swaleio/examples whose scripts run. + default: main + hub_repo: + description: Hub model repo to upload the classifier 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: Draw the few examples + uses: swaleio/duckdb + args: + sql: | + -- The same rows every time: each label's first rows in a fixed hash order. + COPY ( + SELECT text, label FROM ( + SELECT "${{inputs.text_column}}" AS text, "${{inputs.label_column}}"::BIGINT AS label, + row_number() OVER (PARTITION BY "${{inputs.label_column}}" ORDER BY hash("${{inputs.text_column}}")) AS n + FROM '${{inputs.train_data}}') + WHERE n <= ${{inputs.per_label}} + ) TO '${{env.WORKFLOW_STORAGE}}/few-shot.parquet' (FORMAT parquet); + COPY (SELECT "${{inputs.text_column}}" AS text, "${{inputs.label_column}}"::BIGINT AS label FROM '${{inputs.eval_data}}') + TO '${{env.WORKFLOW_STORAGE}}/eval.parquet' (FORMAT parquet); + SELECT label, count(*) AS examples FROM '${{env.WORKFLOW_STORAGE}}/few-shot.parquet' GROUP BY label ORDER BY label; + + train: + name: Train + uses: swaleio/transformers + compute_type: a100-1 + start_on: + - fetch_scripts + - fetch_model + - prepare + args: + script: | + import os, subprocess, sys + + storage = os.environ["WORKFLOW_STORAGE"] + examples = f"{storage}/examples" + for requirements in ("gpu-sentence-transformers.txt", "gpu-setfit.txt"): + subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "--no-deps", "--target", "/tmp/deps", + "-r", f"{examples}/requirements/{requirements}"], check=True) + subprocess.run([sys.executable, f"{examples}/workflows/setfit-classifier/train.py", + "--model", f"{storage}/base-model", "--train", f"{storage}/few-shot.parquet", + "--labels", "${{inputs.labels}}", "--output", f"{storage}/model"], + env={**os.environ, "PYTHONPATH": "/tmp/deps"}, 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"] + examples = f"{storage}/examples" + for requirements in ("gpu-sentence-transformers.txt", "gpu-setfit.txt"): + subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "--no-deps", "--target", "/tmp/deps", + "-r", f"{examples}/requirements/{requirements}"], check=True) + subprocess.run([sys.executable, f"{examples}/workflows/setfit-classifier/predict.py", + "--model", f"{storage}/model", "--eval", f"{storage}/eval.parquet", + "--output", f"{storage}/predictions.parquet"], + env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True) + + score: + name: Score + uses: swaleio/duckdb + start_on: + - predict + args: + sql: | + CREATE TABLE predictions AS SELECT * FROM '${{env.WORKFLOW_STORAGE}}/predictions.parquet'; + CREATE TABLE per_class AS + WITH classes AS (SELECT DISTINCT label AS class FROM predictions) + SELECT string_split($$${{inputs.labels}}$$, ',')[class + 1] AS label, + sum((p.label = class AND p.prediction = class)::INT) AS tp, + sum((p.label <> class AND p.prediction = class)::INT) AS fp, + sum((p.label = class AND p.prediction <> class)::INT) AS fn + FROM classes, predictions p GROUP BY class ORDER BY class; + SELECT label, tp + fn AS rows, + round(CASE WHEN 2 * tp + fp + fn = 0 THEN 0 ELSE 2.0 * tp / (2 * tp + fp + fn) END, 4) AS f1 + FROM per_class; + COPY (SELECT (SELECT count(*) FROM predictions) AS rows, + (SELECT round(avg((label = prediction)::INT), 4) FROM predictions) AS accuracy, + (SELECT round(avg(CASE WHEN 2 * tp + fp + fn = 0 THEN 0 ELSE 2.0 * tp / (2 * tp + fp + fn) END), 4) FROM per_class) AS macro_f1) + 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 Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + source: ${{env.WORKFLOW_STORAGE}}/model + token: ${{secrets.hf_token}} diff --git a/workflows/speech-dataset/README.md b/workflows/speech-dataset/README.md new file mode 100644 index 0000000..c416093 --- /dev/null +++ b/workflows/speech-dataset/README.md @@ -0,0 +1,45 @@ +# Build a speech dataset + +Turns long recordings into a speech-recognition dataset of short clips, each +with its transcription. whisper.cpp transcribes every recording into segments +with start and end times; FFmpeg cuts one clip per segment; and DuckDB packages +the clips and their text as Parquet, with the audio in the shape of a Hugging +Face `Audio` column, ready for training or for the Hub. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Fetch the whisper.cpp model | `swaleio/hf-download` | `cpu-4` | +| For each recording: convert it to 16 kHz mono WAV | `swaleio/ffmpeg` | `cpu-4` | +| For each recording: transcribe it into timed segments | `swaleio/whisper-cpp` | `a100-1` | +| List the segments, keep those within the length range | `swaleio/duckdb` | `cpu-4` | +| Cut one clip per kept segment | `swaleio/ffmpeg` | `cpu-4` | +| Package clips and text into `speech.parquet` | `swaleio/duckdb` | `cpu-4` | +| Upload to the Hub, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +Every step is its own task. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `media_urls` | three poems read for LibriVox | The recordings, as a JSON array of URLs or workspace paths. | +| `whisper_model` | `ggml-large-v3-turbo-q5_0.bin` | Model file in `ggerganov/whisper.cpp`. | +| `language` | `en` | Two-letter language code, or `auto`. | +| `min_seconds` | `1` | Shortest clip kept. | +| `max_seconds` | `30` | Longest clip kept. | +| `hub_repo` | empty | Hub dataset repo to upload the dataset to, as `data/train.parquet`. | + +The upload reads the secret `hf_token`. + +## Output + +`speech.parquet` on the workspace, with `audio` (`bytes` and `path`), +`transcription` and `seconds` for each clip. + +The transcriptions come from a model, not from people. Check a sample before +training on them. + +## Licenses of the defaults + +- Model: [ggerganov/whisper.cpp](https://huggingface.co/ggerganov/whisper.cpp), MIT. +- Recordings: from [LibriVox Short Poetry Collection 140](https://archive.org/details/spc140_1502_librivox), public domain. diff --git a/workflows/speech-dataset/workflow.yaml b/workflows/speech-dataset/workflow.yaml new file mode 100644 index 0000000..f59f66a --- /dev/null +++ b/workflows/speech-dataset/workflow.yaml @@ -0,0 +1,148 @@ +name: Build a speech dataset +description: Transcribes recordings with whisper.cpp, cuts them into one clip per transcribed segment, and packages clips and text as a Parquet speech-recognition dataset. +compute_type: cpu-4 + +inputs: + media_urls: + description: The recordings, as a JSON array of URLs or workspace paths; anything FFmpeg reads. + default: '["https://archive.org/download/spc140_1502_librivox/spc140_blackvulture_wt_64kb.mp3", "https://archive.org/download/spc140_1502_librivox/spc140_gethsemane_db_64kb.mp3", "https://archive.org/download/spc140_1502_librivox/spc140_fromonewhostays_ss_64kb.mp3"]' + whisper_model: + description: File name of the whisper.cpp model in ggerganov/whisper.cpp on the Hub. + default: ggml-large-v3-turbo-q5_0.bin + language: + description: Spoken language as a two-letter code, or auto. + default: en + min_seconds: + description: Shortest clip to keep. + default: "1" + max_seconds: + description: Longest clip to keep. + default: "30" + hub_repo: + description: Hub dataset repo to upload the dataset to, as namespace/name. Leave empty to keep it on the workspace only. + default: "" + +entry_point: main + +blocks: + main: + tasks: + fetch_model: + name: Fetch whisper model + uses: swaleio/hf-download + args: + repo: ggerganov/whisper.cpp + include: ${{inputs.whisper_model}} + dest: ${{env.WORKFLOW_STORAGE}}/whisper + + each_recording: + name: Transcribe each recording + start_on: + - fetch_model + for_each: + items: ${{inputs.media_urls}} + block: transcribe_one + + cut_list: + name: List the segments to cut + uses: swaleio/duckdb + start_on: + - each_recording + args: + sql: | + -- whisper.cpp's JSON has one entry per segment, with offsets in milliseconds. + CREATE TABLE segments AS + SELECT regexp_extract(filename, '(\d+)\.json$', 1)::INT AS recording, + generate_subscripts(transcription, 1) - 1 AS segment, + unnest(transcription).offsets."from" / 1000.0 AS start_s, + unnest(transcription).offsets."to" / 1000.0 AS end_s, + trim(unnest(transcription).text) AS text + FROM read_json('${{env.WORKFLOW_STORAGE}}/transcripts/*.json', filename = true); + CREATE TABLE kept AS + SELECT *, end_s - start_s AS seconds, + recording || '-' || lpad(segment::VARCHAR, 4, '0') AS clip + FROM segments + WHERE end_s - start_s BETWEEN ${{inputs.min_seconds}} AND ${{inputs.max_seconds}} AND text <> ''; + COPY kept TO '${{env.WORKFLOW_STORAGE}}/segments.parquet' (FORMAT parquet); + COPY (SELECT recording, start_s, seconds, clip FROM kept ORDER BY clip) + TO '${{env.WORKFLOW_STORAGE}}/cuts.tsv' (FORMAT csv, DELIMITER '\t', HEADER false); + SELECT count(*) AS segments, count(*) FILTER (seconds BETWEEN ${{inputs.min_seconds}} AND ${{inputs.max_seconds}}) AS kept + FROM (SELECT end_s - start_s AS seconds FROM segments); + + cut: + name: Cut the clips + uses: swaleio/ffmpeg + start_on: + - cut_list + args: + script: | + set -euo pipefail + mkdir -p "$WORKFLOW_STORAGE/clips" + while IFS=$'\t' read -r recording start seconds clip; do + ffmpeg -hide_banner -loglevel error -nostdin -ss "$start" -t "$seconds" \ + -i "$WORKFLOW_STORAGE/wav/$recording.wav" -c:a pcm_s16le "$WORKFLOW_STORAGE/clips/$clip.wav" + done < "$WORKFLOW_STORAGE/cuts.tsv" + ls "$WORKFLOW_STORAGE/clips" | wc -l + + package: + name: Package the dataset + uses: swaleio/duckdb + start_on: + - cut + args: + sql: | + -- The audio column has the shape of a Hugging Face Audio feature: the encoded file and its name. + COPY ( + SELECT {'bytes': b.content, 'path': s.clip || '.wav'} AS audio, + s.text AS transcription, round(s.seconds, 2) AS seconds + FROM '${{env.WORKFLOW_STORAGE}}/segments.parquet' s + JOIN read_blob('${{env.WORKFLOW_STORAGE}}/clips/*.wav') b + ON b.filename LIKE '%/' || s.clip || '.wav' + ORDER BY s.clip + ) TO '${{env.WORKFLOW_STORAGE}}/speech.parquet' (FORMAT parquet); + SELECT count(*) AS clips, round(sum(seconds) / 60, 1) AS minutes, + round(avg(seconds), 1) AS mean_seconds + FROM '${{env.WORKFLOW_STORAGE}}/speech.parquet'; + + publish: + name: Upload when asked + start_on: + - package + if: + condition: ${{inputs.hub_repo}} + true: upload + + transcribe_one: + tasks: + to_wav: + name: Convert to 16 kHz WAV + uses: swaleio/ffmpeg + args: + script: | + set -euo pipefail + mkdir -p "$WORKFLOW_STORAGE/wav" "$WORKFLOW_STORAGE/transcripts" + ffmpeg -hide_banner -loglevel error -i "${{tasks.each_recording.for_each.item}}" \ + -vn -ac 1 -ar 16000 -c:a pcm_s16le "$WORKFLOW_STORAGE/wav/${{tasks.each_recording.for_each.index}}.wav" + transcribe: + name: Transcribe + uses: swaleio/whisper-cpp + compute_type: a100-1 + start_on: + - to_wav + args: + model: ${{env.WORKFLOW_STORAGE}}/whisper/${{inputs.whisper_model}} + audio: ${{env.WORKFLOW_STORAGE}}/wav/${{tasks.each_recording.for_each.index}}.wav + output_prefix: ${{env.WORKFLOW_STORAGE}}/transcripts/${{tasks.each_recording.for_each.index}} + language: ${{inputs.language}} + + upload: + tasks: + upload_dataset: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + repo_type: dataset + source: ${{env.WORKFLOW_STORAGE}}/speech.parquet + path_in_repo: data/train.parquet + token: ${{secrets.hf_token}} diff --git a/workflows/summarization/README.md b/workflows/summarization/README.md new file mode 100644 index 0000000..c9c29ca --- /dev/null +++ b/workflows/summarization/README.md @@ -0,0 +1,49 @@ +# Summarisation + +Fine-tunes a sequence-to-sequence model, such as Flan-T5, to summarise news +articles, then generates a summary of every held-out article and scores the +summaries with ROUGE. Generating needs a GPU; scoring does not, so the two are +separate tasks. + +| 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, print the mean article and summary lengths | `swaleio/duckdb` | `cpu-4` | +| Tokenize articles and summaries ([`preprocess.py`](preprocess.py)) | `swaleio/python-3-13` | `cpu-4` | +| Train ([`train.py`](train.py)) | `swaleio/transformers` | `a100-1` | +| Generate a summary of each eval article, with beam search ([`generate.py`](generate.py)) | `swaleio/transformers` | `a100-1` | +| Score ROUGE-1, ROUGE-2 and ROUGE-L ([`score.py`](score.py)) | `swaleio/python-3-13` | `cpu-4` | +| Upload the model, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +**What stays one script:** the training loop, which holds the model, the +optimizer and the batches together on one GPU. + +These scripts also serve the [translation](../translation) workflow. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `model` | `google/flan-t5-small` | Sequence-to-sequence model to fine-tune. | +| `train_data`, `eval_data` | the train and validation splits of `abisee/cnn_dailymail` 3.0.0 | Parquet files or globs, as DuckDB paths. | +| `source_column`, `target_column` | `article`, `highlights` | Columns holding each article and its reference summary. | +| `train_rows`, `eval_rows` | `10000`, `500` | Rows to use from each. | +| `prefix` | `summarize: ` | Text put before every article, as T5 models expect. | +| `epochs` | `1` | Training epochs. | +| `examples_ref` | `main` | Branch, tag or full commit SHA of this repository whose scripts run. | +| `hub_repo` | empty | Hub 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, each eval article's +reference and generated summary in `predictions.parquet`, and the ROUGE scores +in `metrics.json`. + +## Licenses + +- Model: [google/flan-t5-small](https://huggingface.co/google/flan-t5-small), Apache-2.0. +- Dataset: [abisee/cnn_dailymail](https://huggingface.co/datasets/abisee/cnn_dailymail), Apache-2.0. +- Packages the steps install: Transformers, Tokenizers, Datasets, SentencePiece and the Hugging Face Hub client to tokenize, and rouge-score (with absl-py, NLTK and NumPy) and PyArrow to score, all under permissive licenses (Apache-2.0 and BSD). diff --git a/workflows/summarization/generate.py b/workflows/summarization/generate.py new file mode 100644 index 0000000..399573c --- /dev/null +++ b/workflows/summarization/generate.py @@ -0,0 +1,43 @@ +"""Generates an output for every eval source with a sequence-to-sequence model, on a GPU. + +Used by the summarization and translation workflows. Writes each source, its +reference and the generated text to Parquet; scoring them needs no GPU. +""" + +import argparse + +import pyarrow as pa +import pyarrow.parquet as pq +import torch +from transformers import AutoModelForSeq2SeqLM, AutoTokenizer + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Directory or Hub repo id of the model") + p.add_argument("--eval", required=True, help="Parquet file with source and target columns") + p.add_argument("--output", required=True, help="Parquet file the generated texts are written to") + p.add_argument("--prefix", default="", help="Text put before every source, as in training") + p.add_argument("--source-max-length", type=int, default=512) + p.add_argument("--max-new-tokens", type=int, default=128) + p.add_argument("--batch-size", type=int, default=32) + args = p.parse_args() + + tokenizer = AutoTokenizer.from_pretrained(args.model) + model = AutoModelForSeq2SeqLM.from_pretrained(args.model).cuda().eval() + rows = pq.read_table(args.eval).to_pylist() + outputs = [] + with torch.no_grad(): + for start in range(0, len(rows), args.batch_size): + batch = rows[start:start + args.batch_size] + encoded = tokenizer([args.prefix + r["source"] for r in batch], truncation=True, + max_length=args.source_max_length, padding=True, return_tensors="pt").to("cuda") + generated = model.generate(**encoded, max_new_tokens=args.max_new_tokens, num_beams=4) + outputs += tokenizer.batch_decode(generated, skip_special_tokens=True) + pq.write_table(pa.table({"source": [r["source"] for r in rows], "reference": [r["target"] for r in rows], + "prediction": outputs}), args.output) + print(f"generated {len(outputs)} outputs") + + +if __name__ == "__main__": + main() diff --git a/workflows/summarization/preprocess.py b/workflows/summarization/preprocess.py new file mode 100644 index 0000000..0ada118 --- /dev/null +++ b/workflows/summarization/preprocess.py @@ -0,0 +1,39 @@ +"""Tokenizes source and target texts for a sequence-to-sequence model, on a CPU. + +Used by the summarization and translation workflows. Writes the tokenized train +and eval splits with datasets' save_to_disk. +""" + +import argparse + +from datasets import load_dataset +from transformers import AutoTokenizer + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Hub repo id or directory whose tokenizer to use") + p.add_argument("--train", required=True, help="Parquet file with source and target columns") + p.add_argument("--eval", required=True, help="Parquet file with source and target columns") + p.add_argument("--prefix", default="", help="Text put before every source, such as 'summarize: ' for T5") + p.add_argument("--source-max-length", type=int, default=512) + p.add_argument("--target-max-length", type=int, default=128) + p.add_argument("--output", required=True, help="Directory the tokenized splits are saved under") + args = p.parse_args() + + tokenizer = AutoTokenizer.from_pretrained(args.model) + splits = load_dataset("parquet", data_files={"train": args.train, "eval": args.eval}) + + def tokenize(batch): + encoded = tokenizer([args.prefix + s for s in batch["source"]], truncation=True, max_length=args.source_max_length) + encoded["labels"] = tokenizer(text_target=batch["target"], truncation=True, max_length=args.target_max_length)["input_ids"] + return encoded + + tokenized = splits.map(tokenize, batched=True, remove_columns=["source", "target"]) + for name, split in tokenized.items(): + split.save_to_disk(f"{args.output}/{name}") + print(f"{name}: {len(split)} rows") + + +if __name__ == "__main__": + main() diff --git a/workflows/summarization/score.py b/workflows/summarization/score.py new file mode 100644 index 0000000..4ae6561 --- /dev/null +++ b/workflows/summarization/score.py @@ -0,0 +1,48 @@ +"""Scores generated texts against their references, on a CPU. + +Used by the summarization workflow (ROUGE, with rouge-score) and the +translation workflow (BLEU and chrF, with sacrebleu). Writes the scores to a +JSON file. +""" + +import argparse +import json + +import pyarrow.parquet as pq + + +def rouge(predictions, references): + from rouge_score import rouge_scorer + + scorer = rouge_scorer.RougeScorer(["rouge1", "rouge2", "rougeL"], use_stemmer=True) + totals = {"rouge1": 0.0, "rouge2": 0.0, "rougeL": 0.0} + for prediction, reference in zip(predictions, references): + for name, score in scorer.score(reference, prediction).items(): + totals[name] += score.fmeasure + return {name: round(100 * total / len(predictions), 2) for name, total in totals.items()} + + +def bleu(predictions, references): + import sacrebleu + + return {"bleu": round(sacrebleu.corpus_bleu(predictions, [references]).score, 2), + "chrf": round(sacrebleu.corpus_chrf(predictions, [references]).score, 2)} + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--predictions", required=True, help="Parquet file with reference and prediction columns") + p.add_argument("--metric", choices=["rouge", "bleu"], required=True) + p.add_argument("--output", required=True, help="JSON file the scores are written to") + args = p.parse_args() + + table = pq.read_table(args.predictions).to_pydict() + measure = rouge if args.metric == "rouge" else bleu + scores = {"rows": len(table["prediction"]), **measure(table["prediction"], table["reference"])} + with open(args.output, "w") as f: + json.dump(scores, f, indent=2) + print(json.dumps(scores)) + + +if __name__ == "__main__": + main() diff --git a/workflows/summarization/train.py b/workflows/summarization/train.py new file mode 100644 index 0000000..69eebc7 --- /dev/null +++ b/workflows/summarization/train.py @@ -0,0 +1,57 @@ +"""Fine-tunes a sequence-to-sequence model on tokenized splits, on a GPU. + +Used by the summarization and translation workflows. The training loop is the +one step that stays a single script: it holds the model, the optimizer and the +batches together on one GPU. +""" + +import argparse + +from datasets import load_from_disk +from transformers import ( + AutoModelForSeq2SeqLM, + AutoTokenizer, + DataCollatorForSeq2Seq, + Seq2SeqTrainer, + Seq2SeqTrainingArguments, +) + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Hub repo id or directory of the model to fine-tune") + p.add_argument("--data", required=True, help="Directory holding the tokenized train and eval splits") + p.add_argument("--output", required=True, help="Directory the fine-tuned model is saved to") + p.add_argument("--epochs", type=float, default=3) + p.add_argument("--learning-rate", type=float, default=3e-4) + p.add_argument("--batch-size", type=int, default=16) + p.add_argument("--bf16", action="store_true", help="Train in bfloat16 mixed precision") + args = p.parse_args() + + tokenizer = AutoTokenizer.from_pretrained(args.model) + model = AutoModelForSeq2SeqLM.from_pretrained(args.model) + trainer = Seq2SeqTrainer( + model=model, + args=Seq2SeqTrainingArguments( + output_dir=f"{args.output}-checkpoints", + num_train_epochs=args.epochs, + learning_rate=args.learning_rate, + per_device_train_batch_size=args.batch_size, + per_device_eval_batch_size=args.batch_size, + eval_strategy="epoch", + save_strategy="no", + bf16=args.bf16, + dataloader_num_workers=2, + report_to="none", + ), + train_dataset=load_from_disk(f"{args.data}/train"), + eval_dataset=load_from_disk(f"{args.data}/eval"), + data_collator=DataCollatorForSeq2Seq(tokenizer, model=model), + ) + trainer.train() + trainer.save_model(args.output) + tokenizer.save_pretrained(args.output) + + +if __name__ == "__main__": + main() diff --git a/workflows/summarization/workflow.yaml b/workflows/summarization/workflow.yaml new file mode 100644 index 0000000..5e6236e --- /dev/null +++ b/workflows/summarization/workflow.yaml @@ -0,0 +1,165 @@ +name: Summarisation +description: Fine-tunes a sequence-to-sequence model to summarise news articles, with tokenizing on a CPU, training and generation on a GPU, and ROUGE computed on a CPU. +compute_type: cpu-4 + +inputs: + model: + description: Hub repo id of the sequence-to-sequence model to fine-tune. + default: google/flan-t5-small + train_data: + description: Parquet file or glob of training articles, as a DuckDB path. + default: hf://datasets/abisee/cnn_dailymail/3.0.0/train-00000-of-00003.parquet + eval_data: + description: Parquet file or glob of evaluation articles, as a DuckDB path. + default: hf://datasets/abisee/cnn_dailymail/3.0.0/validation-00000-of-00001.parquet + source_column: + description: Column holding each text to summarise. + default: article + target_column: + description: Column holding each reference summary. + default: highlights + train_rows: + description: Training articles to use. + default: "10000" + eval_rows: + description: Evaluation articles to use. + default: "500" + prefix: + description: Text put before every source, as the model expects. + default: "summarize: " + epochs: + description: Training epochs. + default: "1" + examples_ref: + description: Branch, tag or full commit SHA of swaleio/examples whose scripts run. + default: main + hub_repo: + description: Hub 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 "${{inputs.source_column}}" AS source, "${{inputs.target_column}}" AS target + FROM '${{inputs.train_data}}' LIMIT ${{inputs.train_rows}}) + TO '${{env.WORKFLOW_STORAGE}}/train.parquet' (FORMAT parquet); + COPY (SELECT "${{inputs.source_column}}" AS source, "${{inputs.target_column}}" AS target + FROM '${{inputs.eval_data}}' LIMIT ${{inputs.eval_rows}}) + TO '${{env.WORKFLOW_STORAGE}}/eval.parquet' (FORMAT parquet); + SELECT count(*) AS train_rows, + round(avg(length(source))) AS mean_source_characters, + round(avg(length(target))) AS mean_summary_characters + FROM '${{env.WORKFLOW_STORAGE}}/train.parquet'; + + tokenize: + name: Tokenize + 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-tokenize.txt"], check=True) + subprocess.run([sys.executable, f"{examples}/workflows/summarization/preprocess.py", + "--model", f"{storage}/base-model", "--prefix", "${{inputs.prefix}}", + "--source-max-length", "512", "--target-max-length", "128", + "--train", f"{storage}/train.parquet", "--eval", f"{storage}/eval.parquet", + "--output", f"{storage}/tokenized"], + env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True) + + train: + name: Train + uses: swaleio/transformers + compute_type: a100-1 + start_on: + - tokenize + args: + script: | + import os, subprocess, sys + + storage = os.environ["WORKFLOW_STORAGE"] + subprocess.run([sys.executable, f"{storage}/examples/workflows/summarization/train.py", + "--model", f"{storage}/base-model", "--data", f"{storage}/tokenized", + "--epochs", "${{inputs.epochs}}", "--learning-rate", "3e-4", + "--output", f"{storage}/model"], check=True) + + generate: + name: Generate for 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/summarization/generate.py", + "--model", f"{storage}/model", "--eval", f"{storage}/eval.parquet", + "--prefix", "${{inputs.prefix}}", "--source-max-length", "512", + "--max-new-tokens", "128", "--output", f"{storage}/predictions.parquet"], check=True) + + score: + name: Score + uses: swaleio/python-3-13 + start_on: + - generate + 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-score-rouge.txt"], check=True) + subprocess.run([sys.executable, f"{examples}/workflows/summarization/score.py", + "--predictions", f"{storage}/predictions.parquet", "--metric", "rouge", + "--output", f"{storage}/metrics.json"], + env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True) + + publish: + name: Upload when asked + start_on: + - score + if: + condition: ${{inputs.hub_repo}} + true: upload + + upload: + tasks: + upload_model: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + source: ${{env.WORKFLOW_STORAGE}}/model + token: ${{secrets.hf_token}} diff --git a/workflows/synthetic-reasoning-data/README.md b/workflows/synthetic-reasoning-data/README.md new file mode 100644 index 0000000..e00583c --- /dev/null +++ b/workflows/synthetic-reasoning-data/README.md @@ -0,0 +1,46 @@ +# Synthetic chain-of-thought data + +Builds a reasoning dataset for fine-tuning. A reasoning model solves each +question step by step; a second model, the judge, compares each solution's +final answer with the reference answer; and the solutions judged correct are +kept as chat-format training rows. Solutions that ran out of tokens before +finishing are not judged. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Fetch the generator, and the judge, in parallel | `swaleio/hf-download` | `cpu-4` | +| Write one solve request per question | `swaleio/duckdb` | `cpu-4` | +| Solve | `swaleio/vllm-batch` | `a100-1` | +| Join solutions to questions, count unfinished ones, write one judge request per finished solution | `swaleio/duckdb` | `cpu-4` | +| Judge | `swaleio/vllm-batch` | `a100-1` | +| Keep the correct solutions as `messages` rows | `swaleio/duckdb` | `cpu-4` | +| Upload to the Hub, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +Every step is its own task. The two GPU steps load different models, so each +holds a GPU only for its own pass. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `generator` | `Qwen/Qwen3-1.7B` | Model that solves, reasoning inside `` tags. | +| `judge` | `Qwen/Qwen3-8B` | Model that checks each final answer; it answers `correct` or `incorrect` only. | +| `questions` | the train split of `openai/gsm8k` | Parquet file or glob, as a DuckDB path. | +| `question_column` | `question` | Column holding each question. | +| `answer_column` | `answer` | Column holding each reference answer. | +| `limit` | `500` | Number of questions. | +| `max_tokens` | `4096` | Longest solution, reasoning included. | +| `hub_repo` | empty | Hub dataset repo to upload `reasoning-sft.parquet` to, as `data/train.parquet`. | + +The downloads and the upload read the secret `hf_token`. + +## Output + +`reasoning-sft.parquet` on the workspace: a `messages` column of user question +and assistant solution, the format `swaleio/trl-sft` trains on. +`solutions.parquet` keeps every solution with its `finish_reason`. + +## Licenses of the defaults + +- Models: [Qwen/Qwen3-1.7B](https://huggingface.co/Qwen/Qwen3-1.7B) and [Qwen/Qwen3-8B](https://huggingface.co/Qwen/Qwen3-8B), Apache-2.0. +- Dataset: [openai/gsm8k](https://huggingface.co/datasets/openai/gsm8k), MIT. diff --git a/workflows/synthetic-reasoning-data/workflow.yaml b/workflows/synthetic-reasoning-data/workflow.yaml new file mode 100644 index 0000000..494227f --- /dev/null +++ b/workflows/synthetic-reasoning-data/workflow.yaml @@ -0,0 +1,164 @@ +name: Synthetic chain-of-thought data +description: Has a reasoning model solve maths questions step by step, has a judge model check each final answer against the reference, and keeps the correct solutions as a fine-tuning dataset. +compute_type: cpu-4 + +inputs: + generator: + description: Hub repo id of the model that writes the solutions. Qwen3 models reason inside tags before they answer. + default: Qwen/Qwen3-1.7B + judge: + description: Hub repo id of the model that checks each final answer against the reference. + default: Qwen/Qwen3-8B + questions: + description: Parquet file or glob holding the questions and reference answers, as a DuckDB path. + default: hf://datasets/openai/gsm8k/main/train-*.parquet + question_column: + description: Column holding each question. + default: question + answer_column: + description: Column holding each reference answer. For GSM8K the final number follows ####. + default: answer + limit: + description: Number of questions to solve. + default: "500" + max_tokens: + description: Longest solution, in tokens, reasoning included. + default: "4096" + hub_repo: + description: Hub dataset repo to upload the kept solutions to, as namespace/name. Leave empty to keep them on the workspace only. + default: "" + +entry_point: main + +blocks: + main: + tasks: + fetch_generator: + name: Fetch generator + uses: swaleio/hf-download + args: + repo: ${{inputs.generator}} + dest: ${{env.WORKFLOW_STORAGE}}/generator + token: ${{secrets.hf_token}} + + fetch_judge: + name: Fetch judge + uses: swaleio/hf-download + args: + repo: ${{inputs.judge}} + dest: ${{env.WORKFLOW_STORAGE}}/judge + token: ${{secrets.hf_token}} + + requests: + name: Write solve requests + uses: swaleio/duckdb + args: + sql: | + CREATE TABLE questions AS + SELECT 'q-' || lpad((row_number() OVER () - 1)::VARCHAR, 6, '0') AS custom_id, + "${{inputs.question_column}}" AS question, + "${{inputs.answer_column}}" AS reference + FROM (SELECT * FROM '${{inputs.questions}}' LIMIT ${{inputs.limit}}); + COPY questions TO '${{env.WORKFLOW_STORAGE}}/questions.parquet' (FORMAT parquet); + COPY ( + SELECT custom_id, 'POST' AS method, '/v1/chat/completions' AS url, + {'model': '${{env.WORKFLOW_STORAGE}}/generator', + 'messages': [{'role': 'user', 'content': question || '\n\nSolve this step by step and give the final answer on the last line.'}], + 'max_tokens': ${{inputs.max_tokens}}, + 'temperature': 0.6, 'top_p': 0.95} AS body + FROM questions + ) TO '${{env.WORKFLOW_STORAGE}}/solve-requests.jsonl' (FORMAT json); + + solve: + name: Solve + uses: swaleio/vllm-batch + compute_type: a100-1 + start_on: + - fetch_generator + - requests + args: + model: ${{env.WORKFLOW_STORAGE}}/generator + input_file: ${{env.WORKFLOW_STORAGE}}/solve-requests.jsonl + output_file: ${{env.WORKFLOW_STORAGE}}/solutions.jsonl + + judge_requests: + name: Write judge requests + uses: swaleio/duckdb + start_on: + - solve + args: + sql: | + CREATE TABLE solutions AS + SELECT q.*, + r.response.body.choices[1].message.content AS solution, + r.response.body.choices[1].finish_reason AS finish_reason + FROM '${{env.WORKFLOW_STORAGE}}/questions.parquet' q + JOIN read_json('${{env.WORKFLOW_STORAGE}}/solutions.jsonl') r USING (custom_id); + COPY solutions TO '${{env.WORKFLOW_STORAGE}}/solutions.parquet' (FORMAT parquet); + COPY ( + SELECT custom_id, 'POST' AS method, '/v1/chat/completions' AS url, + {'model': '${{env.WORKFLOW_STORAGE}}/judge', + 'messages': [{'role': 'user', 'content': + 'Question:\n' || question || + '\n\nReference answer:\n' || reference || + '\n\nProposed solution (only its final answer matters):\n' || + regexp_replace(solution, '(?s)^.*', '') || + '\n\nIs the final answer of the proposed solution the same as the reference answer? Answer correct or incorrect.'}], + 'max_tokens': 8, 'temperature': 0, + 'chat_template_kwargs': {'enable_thinking': false}, + 'structured_outputs': {'choice': ['correct', 'incorrect']}} AS body + FROM solutions + WHERE finish_reason = 'stop' + ) TO '${{env.WORKFLOW_STORAGE}}/judge-requests.jsonl' (FORMAT json); + SELECT finish_reason, count(*) AS solutions FROM solutions GROUP BY ALL; + + judge: + name: Judge + uses: swaleio/vllm-batch + compute_type: a100-1 + start_on: + - fetch_judge + - judge_requests + args: + model: ${{env.WORKFLOW_STORAGE}}/judge + input_file: ${{env.WORKFLOW_STORAGE}}/judge-requests.jsonl + output_file: ${{env.WORKFLOW_STORAGE}}/verdicts.jsonl + + keep: + name: Keep correct solutions + uses: swaleio/duckdb + start_on: + - judge + args: + sql: | + CREATE TABLE judged AS + SELECT s.*, trim(v.response.body.choices[1].message.content) AS verdict + FROM '${{env.WORKFLOW_STORAGE}}/solutions.parquet' s + JOIN read_json('${{env.WORKFLOW_STORAGE}}/verdicts.jsonl') v USING (custom_id); + SELECT verdict, count(*) AS solutions FROM judged GROUP BY ALL; + COPY ( + SELECT custom_id, + [{'role': 'user', 'content': question}, + {'role': 'assistant', 'content': solution}] AS messages + FROM judged WHERE verdict = 'correct' ORDER BY custom_id + ) TO '${{env.WORKFLOW_STORAGE}}/reasoning-sft.parquet' (FORMAT parquet); + + publish: + name: Upload when asked + start_on: + - keep + if: + condition: ${{inputs.hub_repo}} + true: upload + + upload: + tasks: + upload_dataset: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + repo_type: dataset + source: ${{env.WORKFLOW_STORAGE}}/reasoning-sft.parquet + path_in_repo: data/train.parquet + token: ${{secrets.hf_token}} diff --git a/workflows/tabular/README.md b/workflows/tabular/README.md new file mode 100644 index 0000000..b93bf54 --- /dev/null +++ b/workflows/tabular/README.md @@ -0,0 +1,46 @@ +# Tabular classification and regression + +Trains a gradient-boosted trees model on a table with scikit-learn, entirely on +CPUs: DuckDB profiles the table and splits it, the model trains on one split, +and a separate task evaluates it on the other. Text columns are used as +categorical features directly, with no encoding step. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Fetch this repository's scripts at `examples_ref` | `swaleio/git-clone` | `cpu-4` | +| Profile every column and the target, split the rows | `swaleio/duckdb` | `cpu-4` | +| Train ([`train.py`](train.py)) | `swaleio/python-3-13` | `cpu-4` | +| Evaluate on the held-out rows ([`evaluate.py`](evaluate.py)) | `swaleio/python-3-13` | `cpu-4` | +| Upload the model, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +**What stays one script:** training, which is a single scikit-learn `fit()`. + +The default predicts whether a person's income is over $50,000 from census +data. For regression, run it with `data` set to +`hf://datasets/gvlassis/california_housing/data/train-00000-of-00001.parquet`, +`target` to `MedHouseVal` and `task` to `regression`, which predicts house +values. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `data` | `scikit-learn/adult-census-income` | CSV or Parquet file of the table, as a DuckDB path. | +| `target` | `income` | Column to predict. | +| `task` | `classification` | `classification` or `regression`. | +| `test_percent` | `20` | Percentage of rows held out. | +| `examples_ref` | `main` | Branch, tag or full commit SHA of this repository whose scripts run. | +| `hub_repo` | empty | Hub model repo to upload the model to. | + +The upload reads the secret `hf_token`. + +## Output + +`model/model.joblib` and `model/features.json` on the workspace, the scores in +`metrics.json`, and each held-out row's prediction in `predictions.parquet`. +A `joblib` file runs code when it is loaded: load only models you trust. + +## Licenses + +- Datasets: [scikit-learn/adult-census-income](https://huggingface.co/datasets/scikit-learn/adult-census-income), CC0-1.0, and, for regression, [gvlassis/california_housing](https://huggingface.co/datasets/gvlassis/california_housing), MIT. +- Packages the steps install: scikit-learn, pandas, SciPy, joblib and threadpoolctl (BSD-3-Clause), PyArrow (Apache-2.0) and narwhals (MIT), with NumPy (BSD-3-Clause). diff --git a/workflows/tabular/evaluate.py b/workflows/tabular/evaluate.py new file mode 100644 index 0000000..45e0422 --- /dev/null +++ b/workflows/tabular/evaluate.py @@ -0,0 +1,49 @@ +"""Evaluates the trained model on the held-out rows, on a CPU, with scikit-learn. + +Classification reports accuracy, macro F1 and, for two classes, ROC AUC; +regression reports mean absolute error, root mean squared error and R squared. +Writes the scores to a JSON file and each row's prediction to Parquet. +""" + +import argparse +import json + +import joblib +import pandas as pd +from sklearn import metrics + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Directory holding model.joblib and features.json") + p.add_argument("--test", required=True, help="Parquet file of held-out rows") + p.add_argument("--output", required=True, help="JSON file the scores are written to") + p.add_argument("--predictions", required=True, help="Parquet file the predictions are written to") + args = p.parse_args() + + model = joblib.load(f"{args.model}/model.joblib") + with open(f"{args.model}/features.json") as f: + spec = json.load(f) + frame = pd.read_parquet(args.test) + x, y = frame[spec["features"]].copy(), frame[spec["target"]] + for column, categories in spec["categories"].items(): + x[column] = pd.Categorical(x[column], categories=categories) + predicted = model.predict(x) + if spec["task"] == "classification": + scores = {"accuracy": metrics.accuracy_score(y, predicted), + "macro_f1": metrics.f1_score(y, predicted, average="macro")} + if len(model.classes_) == 2: + scores["roc_auc"] = metrics.roc_auc_score(y, model.predict_proba(x)[:, 1]) + else: + scores = {"mean_absolute_error": metrics.mean_absolute_error(y, predicted), + "root_mean_squared_error": metrics.root_mean_squared_error(y, predicted), + "r2": metrics.r2_score(y, predicted)} + scores = {"rows": len(y), **{k: round(float(v), 4) for k, v in scores.items()}} + with open(args.output, "w") as f: + json.dump(scores, f, indent=2) + pd.DataFrame({"actual": y, "predicted": predicted}).to_parquet(args.predictions) + print(json.dumps(scores)) + + +if __name__ == "__main__": + main() diff --git a/workflows/tabular/train.py b/workflows/tabular/train.py new file mode 100644 index 0000000..53023cb --- /dev/null +++ b/workflows/tabular/train.py @@ -0,0 +1,47 @@ +"""Trains a gradient-boosted trees model on a table, on a CPU, with scikit-learn. + +Text columns become categorical features that the model splits on directly; no +encoding step is needed. Saves the fitted model with joblib and the feature +list beside it. Training is one scikit-learn fit() call, the one step of the +workflow that stays a single script. +""" + +import argparse +import json + +import joblib +import pandas as pd +from sklearn.ensemble import HistGradientBoostingClassifier, HistGradientBoostingRegressor + + +def features(frame, target): + frame = frame.drop(columns=[target]) + for column in frame.columns: + if frame[column].dtype == object or str(frame[column].dtype) == "str": + frame[column] = frame[column].astype("category") + return frame + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--train", required=True, help="Parquet file of training rows") + p.add_argument("--target", required=True, help="Column to predict") + p.add_argument("--task", choices=["classification", "regression"], required=True) + p.add_argument("--output", required=True, help="Directory the model is saved to") + args = p.parse_args() + + frame = pd.read_parquet(args.train) + x, y = features(frame, args.target), frame[args.target] + estimator = HistGradientBoostingClassifier if args.task == "classification" else HistGradientBoostingRegressor + model = estimator(categorical_features="from_dtype", max_iter=300, early_stopping=True, random_state=0) + model.fit(x, y) + joblib.dump(model, f"{args.output}/model.joblib") + with open(f"{args.output}/features.json", "w") as f: + json.dump({"target": args.target, "task": args.task, + "categories": {c: list(x[c].cat.categories) for c in x.columns if x[c].dtype.name == "category"}, + "features": list(x.columns)}, f, indent=2) + print(f"trained on {len(x)} rows, {x.shape[1]} features, {model.n_iter_} boosting iterations") + + +if __name__ == "__main__": + main() diff --git a/workflows/tabular/workflow.yaml b/workflows/tabular/workflow.yaml new file mode 100644 index 0000000..8dfdbb1 --- /dev/null +++ b/workflows/tabular/workflow.yaml @@ -0,0 +1,109 @@ +name: Tabular classification and regression +description: Profiles a table and splits it with SQL, trains a gradient-boosted trees model with scikit-learn, and evaluates it on held-out rows, all on CPUs. +compute_type: cpu-4 + +inputs: + data: + description: CSV or Parquet file of the table, as a DuckDB path. + default: hf://datasets/scikit-learn/adult-census-income/adult.csv + target: + description: Column to predict. + default: income + task: + description: classification for a class column, regression for a number. + default: classification + test_percent: + description: Percentage of rows held out for evaluation. + default: "20" + examples_ref: + description: Branch, tag or full commit SHA of swaleio/examples whose scripts run. + default: main + hub_repo: + description: Hub model repo to upload the 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 + + profile_and_split: + name: Profile and split + uses: swaleio/duckdb + args: + sql: | + CREATE TABLE source AS SELECT * FROM '${{inputs.data}}'; + SUMMARIZE source; + SELECT "${{inputs.target}}", count(*) AS rows FROM source GROUP BY ALL ORDER BY rows DESC LIMIT 20; + -- A row's hash decides its split, so a rerun splits the same way. + CREATE TABLE split AS + SELECT *, hash(row_number() OVER ()) % 100 < ${{inputs.test_percent}} AS held_out FROM source; + COPY (SELECT * EXCLUDE (held_out) FROM split WHERE NOT held_out) + TO '${{env.WORKFLOW_STORAGE}}/train.parquet' (FORMAT parquet); + COPY (SELECT * EXCLUDE (held_out) FROM split WHERE held_out) + TO '${{env.WORKFLOW_STORAGE}}/test.parquet' (FORMAT parquet); + SELECT held_out, count(*) AS rows FROM split GROUP BY ALL; + + train: + name: Train + uses: swaleio/python-3-13 + start_on: + - fetch_scripts + - profile_and_split + args: + script: | + import os, subprocess, sys + + storage = os.environ["WORKFLOW_STORAGE"] + examples = f"{storage}/examples" + os.makedirs(f"{storage}/model", exist_ok=True) + subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "--target", "/tmp/deps", + "-r", f"{examples}/requirements/cpu-tabular.txt"], check=True) + subprocess.run([sys.executable, f"{examples}/workflows/tabular/train.py", + "--train", f"{storage}/train.parquet", "--target", "${{inputs.target}}", + "--task", "${{inputs.task}}", "--output", f"{storage}/model"], + env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True) + + evaluate: + name: Evaluate + uses: swaleio/python-3-13 + start_on: + - train + 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-tabular.txt"], check=True) + subprocess.run([sys.executable, f"{examples}/workflows/tabular/evaluate.py", + "--model", f"{storage}/model", "--test", f"{storage}/test.parquet", + "--output", f"{storage}/metrics.json", "--predictions", f"{storage}/predictions.parquet"], + env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True) + + publish: + name: Upload when asked + start_on: + - evaluate + if: + condition: ${{inputs.hub_repo}} + true: upload + + upload: + tasks: + upload_model: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + source: ${{env.WORKFLOW_STORAGE}}/model + token: ${{secrets.hf_token}} diff --git a/workflows/text-classification/README.md b/workflows/text-classification/README.md new file mode 100644 index 0000000..609396b --- /dev/null +++ b/workflows/text-classification/README.md @@ -0,0 +1,47 @@ +# Text classification + +Fine-tunes an encoder model, such as ModernBERT, to put texts into classes, and +measures it on held-out rows. The work is split so that only training and +prediction hold a GPU: the splits are prepared with SQL, tokenizing runs on a +CPU, and the scores are computed with SQL. + +| 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 train and eval splits, count each label | `swaleio/duckdb` | `cpu-4` | +| Tokenize both splits ([`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` | +| Upload the model, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +**What stays one script:** the training loop, in `train.py`. The model, the +optimizer and the batches live together on one GPU for the whole of training, +so it cannot be cut into tasks. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `model` | `answerdotai/ModernBERT-base` | Encoder model to fine-tune. | +| `train_data`, `eval_data` | the train and validation splits of `google-research-datasets/poem_sentiment` | Parquet files or globs, as DuckDB paths. | +| `text_column` | `verse_text` | Column holding the text. | +| `label_column` | `label` | Column holding the label, as a number from 0. | +| `labels` | `negative,positive,no_impact,mixed` | Label names in label-number order. | +| `epochs` | `5` | Training epochs. | +| `examples_ref` | `main` | Branch, tag or full commit SHA of this repository whose scripts run. | +| `hub_repo` | empty | Hub 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 `metrics.json` with the accuracy and macro F1. + +## Licenses + +- Model: [answerdotai/ModernBERT-base](https://huggingface.co/answerdotai/ModernBERT-base), Apache-2.0. +- Dataset: [google-research-datasets/poem_sentiment](https://huggingface.co/datasets/google-research-datasets/poem_sentiment), CC BY 4.0. +- Packages the tokenize step installs: Transformers, Tokenizers, Datasets, SentencePiece and the Hugging Face Hub client, Apache-2.0. diff --git a/workflows/text-classification/predict.py b/workflows/text-classification/predict.py new file mode 100644 index 0000000..f5ba3c2 --- /dev/null +++ b/workflows/text-classification/predict.py @@ -0,0 +1,45 @@ +"""Predicts a label, or a number, for every row of the tokenized eval split, on a GPU. + +Writes the true and predicted values to Parquet; scoring them is a +separate step that needs no GPU. +""" + +import argparse + +import pyarrow as pa +import pyarrow.parquet as pq +import torch +from datasets import load_from_disk +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Directory of the fine-tuned model") + p.add_argument("--data", required=True, help="Directory of the tokenized eval split") + p.add_argument("--output", required=True, help="Parquet file the predictions are written to") + p.add_argument("--batch-size", type=int, default=64) + args = p.parse_args() + + tokenizer = AutoTokenizer.from_pretrained(args.model) + model = AutoModelForSequenceClassification.from_pretrained(args.model).cuda().eval() + rows = load_from_disk(args.data) + labels = rows["label"] + loader = DataLoader( + rows.remove_columns(["label"]), batch_size=args.batch_size, collate_fn=DataCollatorWithPadding(tokenizer) + ) + predictions = [] + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): + for batch in loader: + logits = model(**{k: v.cuda() for k, v in batch.items()}).logits + if model.config.num_labels == 1: + predictions += logits[:, 0].float().tolist() + else: + predictions += logits.argmax(-1).tolist() + pq.write_table(pa.table({"label": labels, "prediction": predictions}), args.output) + print(f"predicted {len(predictions)} rows") + + +if __name__ == "__main__": + main() diff --git a/workflows/text-classification/preprocess.py b/workflows/text-classification/preprocess.py new file mode 100644 index 0000000..214fb2d --- /dev/null +++ b/workflows/text-classification/preprocess.py @@ -0,0 +1,35 @@ +"""Tokenizes the train and eval splits for sequence classification, on a CPU. + +Writes each split with datasets' save_to_disk, so the training task loads token +ids instead of text and holds no GPU while tokenizing. +""" + +import argparse + +from datasets import load_dataset +from transformers import AutoTokenizer + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Hub repo id or directory whose tokenizer to use") + p.add_argument("--train", required=True, help="Parquet file with text and label columns") + p.add_argument("--eval", required=True, help="Parquet file with text and label columns") + p.add_argument("--max-length", type=int, default=256) + p.add_argument("--output", required=True, help="Directory the tokenized splits are saved under") + args = p.parse_args() + + tokenizer = AutoTokenizer.from_pretrained(args.model) + splits = load_dataset("parquet", data_files={"train": args.train, "eval": args.eval}) + + def tokenize(batch): + return tokenizer(batch["text"], truncation=True, max_length=args.max_length) + + tokenized = splits.map(tokenize, batched=True, remove_columns=["text"]) + for name, split in tokenized.items(): + split.save_to_disk(f"{args.output}/{name}") + print(f"{name}: {len(split)} rows, longest {max(len(ids) for ids in split['input_ids'])} tokens") + + +if __name__ == "__main__": + main() diff --git a/workflows/text-classification/train.py b/workflows/text-classification/train.py new file mode 100644 index 0000000..392c968 --- /dev/null +++ b/workflows/text-classification/train.py @@ -0,0 +1,71 @@ +"""Fine-tunes a sequence-classification or regression model on tokenized splits, 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. +""" + +import argparse + +from datasets import Value, load_from_disk +from transformers import ( + AutoModelForSequenceClassification, + AutoTokenizer, + DataCollatorWithPadding, + Trainer, + TrainingArguments, +) + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Hub repo id or directory of the model to fine-tune") + p.add_argument("--data", required=True, help="Directory holding the tokenized train and eval splits") + p.add_argument("--labels", help="Label names, separated by commas, in label-number order") + p.add_argument("--regression", action="store_true", help="Predict one number per text instead of a class") + p.add_argument("--output", required=True, help="Directory the fine-tuned model is saved to") + p.add_argument("--epochs", type=float, default=3) + p.add_argument("--learning-rate", type=float, default=5e-5) + p.add_argument("--batch-size", type=int, default=32) + args = p.parse_args() + + tokenizer = AutoTokenizer.from_pretrained(args.model) + train = load_from_disk(f"{args.data}/train") + evaluation = load_from_disk(f"{args.data}/eval") + if args.regression: + model = AutoModelForSequenceClassification.from_pretrained(args.model, num_labels=1, problem_type="regression") + train = train.cast_column("label", Value("float32")) + evaluation = evaluation.cast_column("label", Value("float32")) + else: + labels = args.labels.split(",") + model = AutoModelForSequenceClassification.from_pretrained( + args.model, + num_labels=len(labels), + id2label=dict(enumerate(labels)), + label2id={label: i for i, label in enumerate(labels)}, + ) + + trainer = Trainer( + model=model, + args=TrainingArguments( + output_dir=f"{args.output}-checkpoints", + num_train_epochs=args.epochs, + learning_rate=args.learning_rate, + per_device_train_batch_size=args.batch_size, + per_device_eval_batch_size=args.batch_size, + eval_strategy="epoch", + save_strategy="no", + bf16=True, + dataloader_num_workers=2, + report_to="none", + ), + train_dataset=train, + eval_dataset=evaluation, + data_collator=DataCollatorWithPadding(tokenizer), + ) + trainer.train() + trainer.save_model(args.output) + tokenizer.save_pretrained(args.output) + + +if __name__ == "__main__": + main() diff --git a/workflows/text-classification/workflow.yaml b/workflows/text-classification/workflow.yaml new file mode 100644 index 0000000..bf6a363 --- /dev/null +++ b/workflows/text-classification/workflow.yaml @@ -0,0 +1,161 @@ +name: Text classification +description: Fine-tunes an encoder model to classify text, with tokenizing on a CPU, training and prediction on a GPU, and accuracy and macro F1 computed in SQL. +compute_type: cpu-4 + +inputs: + model: + description: Hub repo id of the encoder model to fine-tune. + default: answerdotai/ModernBERT-base + train_data: + description: Parquet file or glob of training rows, as a DuckDB path. + default: hf://datasets/google-research-datasets/poem_sentiment/data/train-00000-of-00001.parquet + eval_data: + description: Parquet file or glob of evaluation rows, as a DuckDB path. + default: hf://datasets/google-research-datasets/poem_sentiment/data/validation-00000-of-00001.parquet + text_column: + description: Column holding the text. + default: verse_text + label_column: + description: Column holding the label, as a number from 0. + default: label + labels: + description: Label names, separated by commas, in label-number order. + default: negative,positive,no_impact,mixed + epochs: + description: Training epochs. + default: "5" + examples_ref: + description: Branch, tag or full commit SHA of swaleio/examples whose scripts run. + default: main + hub_repo: + description: Hub 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 "${{inputs.text_column}}" AS text, "${{inputs.label_column}}"::BIGINT AS label FROM '${{inputs.train_data}}') + TO '${{env.WORKFLOW_STORAGE}}/train.parquet' (FORMAT parquet); + COPY (SELECT "${{inputs.text_column}}" AS text, "${{inputs.label_column}}"::BIGINT AS label FROM '${{inputs.eval_data}}') + TO '${{env.WORKFLOW_STORAGE}}/eval.parquet' (FORMAT parquet); + SELECT 'train' AS split, label, count(*) AS rows FROM '${{env.WORKFLOW_STORAGE}}/train.parquet' GROUP BY ALL + UNION ALL + SELECT 'eval', label, count(*) FROM '${{env.WORKFLOW_STORAGE}}/eval.parquet' GROUP BY ALL + ORDER BY split DESC, label; + + tokenize: + name: Tokenize + 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-tokenize.txt"], check=True) + subprocess.run([sys.executable, f"{examples}/workflows/text-classification/preprocess.py", + "--model", f"{storage}/base-model", + "--train", f"{storage}/train.parquet", "--eval", f"{storage}/eval.parquet", + "--output", f"{storage}/tokenized"], + env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True) + + train: + name: Train + uses: swaleio/transformers + compute_type: a100-1 + start_on: + - tokenize + args: + script: | + import os, subprocess, sys + + storage = os.environ["WORKFLOW_STORAGE"] + subprocess.run([sys.executable, f"{storage}/examples/workflows/text-classification/train.py", + "--model", f"{storage}/base-model", "--data", f"{storage}/tokenized", + "--labels", "${{inputs.labels}}", "--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/text-classification/predict.py", + "--model", f"{storage}/model", "--data", f"{storage}/tokenized/eval", + "--output", f"{storage}/predictions.parquet"], check=True) + + score: + name: Score + uses: swaleio/duckdb + start_on: + - predict + args: + sql: | + CREATE TABLE predictions AS SELECT * FROM '${{env.WORKFLOW_STORAGE}}/predictions.parquet'; + CREATE TABLE per_class AS + WITH classes AS (SELECT DISTINCT label AS class FROM predictions) + SELECT string_split($$${{inputs.labels}}$$, ',')[class + 1] AS label, + sum((p.label = class AND p.prediction = class)::INT) AS tp, + sum((p.label <> class AND p.prediction = class)::INT) AS fp, + sum((p.label = class AND p.prediction <> class)::INT) AS fn + FROM classes, predictions p GROUP BY class ORDER BY class; + SELECT label, tp + fn AS rows, + round(CASE WHEN 2 * tp + fp + fn = 0 THEN 0 ELSE 2.0 * tp / (2 * tp + fp + fn) END, 4) AS f1 + FROM per_class; + COPY (SELECT (SELECT count(*) FROM predictions) AS rows, + (SELECT round(avg((label = prediction)::INT), 4) FROM predictions) AS accuracy, + (SELECT round(avg(CASE WHEN 2 * tp + fp + fn = 0 THEN 0 ELSE 2.0 * tp / (2 * tp + fp + fn) END), 4) FROM per_class) AS macro_f1) + 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 Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + source: ${{env.WORKFLOW_STORAGE}}/model + token: ${{secrets.hf_token}} diff --git a/workflows/text-regression/README.md b/workflows/text-regression/README.md new file mode 100644 index 0000000..fb14396 --- /dev/null +++ b/workflows/text-regression/README.md @@ -0,0 +1,49 @@ +# Text regression + +Fine-tunes an encoder model to predict a number for each text. The default data +is FineWeb-Edu's set of web pages scored from 0 to 5 for educational value, the +kind of scorer used to filter pre-training data. Only training and prediction +hold a GPU. + +| 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 train and eval splits, print each one's mean and spread | `swaleio/duckdb` | `cpu-4` | +| Tokenize both splits ([`preprocess.py`](../text-classification/preprocess.py)) | `swaleio/python-3-13` | `cpu-4` | +| Train with one output and a mean-squared-error loss ([`train.py`](../text-classification/train.py) `--regression`) | `swaleio/transformers` | `a100-1` | +| Predict the eval split ([`predict.py`](../text-classification/predict.py)) | `swaleio/transformers` | `a100-1` | +| Compute mean squared error, mean absolute error, Pearson correlation and rounded accuracy | `swaleio/duckdb` | `cpu-4` | +| Upload the model, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +The scripts are the [text classification](../text-classification) 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` | `answerdotai/ModernBERT-base` | Encoder model to fine-tune. | +| `train_data`, `eval_data` | two shards of `HuggingFaceFW/fineweb-edu-llama3-annotations` | Parquet files or globs, as DuckDB paths. | +| `text_column` | `text` | Column holding the text. | +| `target_column` | `score` | Column holding the number to predict. | +| `train_rows`, `eval_rows` | `20000`, `2000` | Rows to use from each. | +| `epochs` | `2` | Training epochs. | +| `examples_ref` | `main` | Branch, tag or full commit SHA of this repository whose scripts run. | +| `hub_repo` | empty | Hub 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`. + +## Licenses + +- Model: [answerdotai/ModernBERT-base](https://huggingface.co/answerdotai/ModernBERT-base), Apache-2.0. +- Dataset: [HuggingFaceFW/fineweb-edu-llama3-annotations](https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu-llama3-annotations), ODC-By 1.0; its texts come from FineWeb, also ODC-By, and Common Crawl's terms of use apply. +- Packages the tokenize step installs: Transformers, Tokenizers, Datasets, SentencePiece and the Hugging Face Hub client, Apache-2.0. diff --git a/workflows/text-regression/workflow.yaml b/workflows/text-regression/workflow.yaml new file mode 100644 index 0000000..d5967dc --- /dev/null +++ b/workflows/text-regression/workflow.yaml @@ -0,0 +1,160 @@ +name: Text regression +description: Fine-tunes an encoder model to predict a number for each text, here an educational-value score, with tokenizing on a CPU, training on a GPU, and error measures computed in SQL. +compute_type: cpu-4 + +inputs: + model: + description: Hub repo id of the encoder model to fine-tune. + default: answerdotai/ModernBERT-base + train_data: + description: Parquet file or glob of training rows, as a DuckDB path. + default: hf://datasets/HuggingFaceFW/fineweb-edu-llama3-annotations/data/train-00000-of-00008.parquet + eval_data: + description: Parquet file or glob of evaluation rows, as a DuckDB path. + default: hf://datasets/HuggingFaceFW/fineweb-edu-llama3-annotations/data/train-00001-of-00008.parquet + text_column: + description: Column holding the text. + default: text + target_column: + description: Column holding the number to predict. + default: score + train_rows: + description: Training rows to use. + default: "20000" + eval_rows: + description: Evaluation rows to use. + default: "2000" + epochs: + description: Training epochs. + default: "2" + examples_ref: + description: Branch, tag or full commit SHA of swaleio/examples whose scripts run. + default: main + hub_repo: + description: Hub 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 "${{inputs.text_column}}" AS text, "${{inputs.target_column}}"::DOUBLE AS label + FROM '${{inputs.train_data}}' LIMIT ${{inputs.train_rows}}) + TO '${{env.WORKFLOW_STORAGE}}/train.parquet' (FORMAT parquet); + COPY (SELECT "${{inputs.text_column}}" AS text, "${{inputs.target_column}}"::DOUBLE AS label + FROM '${{inputs.eval_data}}' LIMIT ${{inputs.eval_rows}}) + TO '${{env.WORKFLOW_STORAGE}}/eval.parquet' (FORMAT parquet); + SELECT 'train' AS split, count(*) AS rows, round(avg(label), 3) AS mean, round(stddev(label), 3) AS std + FROM '${{env.WORKFLOW_STORAGE}}/train.parquet' + UNION ALL + SELECT 'eval', count(*), round(avg(label), 3), round(stddev(label), 3) + FROM '${{env.WORKFLOW_STORAGE}}/eval.parquet'; + + tokenize: + name: Tokenize + 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-tokenize.txt"], check=True) + subprocess.run([sys.executable, f"{examples}/workflows/text-classification/preprocess.py", + "--model", f"{storage}/base-model", "--max-length", "512", + "--train", f"{storage}/train.parquet", "--eval", f"{storage}/eval.parquet", + "--output", f"{storage}/tokenized"], + env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True) + + train: + name: Train + uses: swaleio/transformers + compute_type: a100-1 + start_on: + - tokenize + args: + script: | + import os, subprocess, sys + + storage = os.environ["WORKFLOW_STORAGE"] + subprocess.run([sys.executable, f"{storage}/examples/workflows/text-classification/train.py", + "--model", f"{storage}/base-model", "--data", f"{storage}/tokenized", "--regression", + "--epochs", "${{inputs.epochs}}", "--batch-size", "16", + "--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/text-classification/predict.py", + "--model", f"{storage}/model", "--data", f"{storage}/tokenized/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((prediction - label) ^ 2), 4) AS mean_squared_error, + round(avg(abs(prediction - label)), 4) AS mean_absolute_error, + round(corr(prediction, label), 4) AS pearson, + round(avg((round(prediction) = label)::INT), 4) AS rounded_accuracy + 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 Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + source: ${{env.WORKFLOW_STORAGE}}/model + token: ${{secrets.hf_token}} diff --git a/workflows/token-classification/README.md b/workflows/token-classification/README.md new file mode 100644 index 0000000..61aae7f --- /dev/null +++ b/workflows/token-classification/README.md @@ -0,0 +1,47 @@ +# Token classification + +Fine-tunes an encoder model to tag named entities, word by word, and scores it +the way named-entity recognition is usually scored: an entity counts only when +its type and its exact span of words are right. The default data is WIESP 2022, +entities such as instruments, missions and organisations in astrophysics +papers. + +| 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 the most frequent entity types | `swaleio/duckdb` | `cpu-4` | +| Tokenize and align each word's tag to its first sub-word token ([`preprocess.py`](preprocess.py)) | `swaleio/python-3-13` | `cpu-4` | +| Train ([`train.py`](train.py)) | `swaleio/transformers` | `a100-1` | +| Tag the eval split ([`predict.py`](predict.py)) | `swaleio/transformers` | `a100-1` | +| Score entities: precision, recall and F1, overall and per type ([`score.py`](score.py)) | `swaleio/python-3-13` | `cpu-4` | +| Upload the model, when `hub_repo` is set | `swaleio/hf-upload` | `cpu-4` | + +**What stays one script:** the training loop, which holds the model, the +optimizer and the batches together on one GPU. The scorer uses only Python's +standard library. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `model` | `google-bert/bert-base-cased` | Encoder model whose tokenizer accepts text split into words. | +| `train_data`, `eval_data` | the train and validation splits of `adsabs/WIESP2022-NER` | Parquet files or globs, as DuckDB paths. | +| `tokens_column` | `tokens` | Column holding each sentence as a list of words. | +| `tags_column` | `ner_tags` | Column holding the IOB2 tags, such as `B-Telescope`. | +| `epochs` | `4` | Training epochs. | +| `examples_ref` | `main` | Branch, tag or full commit SHA of this repository whose scripts run. | +| `hub_repo` | empty | Hub 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, each sentence's gold and +predicted tags in `predictions.jsonl`, and the scores in `metrics.json`. + +## Licenses + +- Model: [google-bert/bert-base-cased](https://huggingface.co/google-bert/bert-base-cased), Apache-2.0. +- Dataset: [adsabs/WIESP2022-NER](https://huggingface.co/datasets/adsabs/WIESP2022-NER), CC BY 4.0. +- Packages the tokenize step installs: Transformers, Tokenizers, Datasets, SentencePiece and the Hugging Face Hub client, Apache-2.0. diff --git a/workflows/token-classification/predict.py b/workflows/token-classification/predict.py new file mode 100644 index 0000000..d254318 --- /dev/null +++ b/workflows/token-classification/predict.py @@ -0,0 +1,40 @@ +"""Tags every word of the eval split with the fine-tuned model, on a GPU. + +Each word takes the prediction of its first sub-word token, so the predicted +tags line up with the gold tags word by word. Writes one JSON line per sentence. +""" + +import argparse +import json + +import torch +from datasets import load_from_disk +from transformers import AutoModelForTokenClassification, AutoTokenizer + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Directory of the fine-tuned model") + p.add_argument("--data", required=True, help="Directory of the tokenized eval split") + p.add_argument("--output", required=True, help="JSON Lines file the gold and predicted tags are written to") + args = p.parse_args() + + tokenizer = AutoTokenizer.from_pretrained(args.model) + model = AutoModelForTokenClassification.from_pretrained(args.model).cuda().eval() + id2label = model.config.id2label + sentences = load_from_disk(args.data) + with open(args.output, "w") as out, torch.no_grad(): + for sentence in sentences: + ids = torch.tensor([sentence["input_ids"]]).cuda() + predicted = model(input_ids=ids).logits[0].argmax(-1).tolist() + gold, guess = [], [] + for label, prediction in zip(sentence["labels"], predicted): + if label != -100: + gold.append(id2label[label]) + guess.append(id2label[prediction]) + out.write(json.dumps({"gold": gold, "predicted": guess}) + "\n") + print(f"tagged {len(sentences)} sentences") + + +if __name__ == "__main__": + main() diff --git a/workflows/token-classification/preprocess.py b/workflows/token-classification/preprocess.py new file mode 100644 index 0000000..3ed1063 --- /dev/null +++ b/workflows/token-classification/preprocess.py @@ -0,0 +1,52 @@ +"""Tokenizes word-split sentences and aligns their tags to sub-word tokens, on a CPU. + +The first sub-word token of each word gets the word's tag; the others, and the +special tokens, get -100 so the loss ignores them. The label list, read from the +training split, is saved beside the splits. +""" + +import argparse +import json + +from datasets import load_dataset +from transformers import AutoTokenizer + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Hub repo id or directory whose tokenizer to use") + p.add_argument("--train", required=True, help="Parquet file with tokens and tags columns") + p.add_argument("--eval", required=True, help="Parquet file with tokens and tags columns") + p.add_argument("--max-length", type=int, default=512) + p.add_argument("--output", required=True, help="Directory the tokenized splits and labels.json are saved under") + args = p.parse_args() + + tokenizer = AutoTokenizer.from_pretrained(args.model) + splits = load_dataset("parquet", data_files={"train": args.train, "eval": args.eval}) + tags = sorted({tag for row in splits["train"]["tags"] for tag in row} | {"O"}, key=lambda t: (t != "O", t)) + label_id = {tag: i for i, tag in enumerate(tags)} + + def tokenize(batch): + encoded = tokenizer(batch["tokens"], is_split_into_words=True, truncation=True, max_length=args.max_length) + labels = [] + for i, word_tags in enumerate(batch["tags"]): + previous, row = None, [] + for word in encoded.word_ids(batch_index=i): + # A tag the training split never had counts as O. + row.append(-100 if word is None or word == previous else label_id.get(word_tags[word], 0)) + previous = word + labels.append(row) + encoded["labels"] = labels + return encoded + + tokenized = splits.map(tokenize, batched=True, remove_columns=["tags"]) + for name, split in tokenized.items(): + split.save_to_disk(f"{args.output}/{name}") + print(f"{name}: {len(split)} sentences") + with open(f"{args.output}/labels.json", "w") as f: + json.dump(tags, f) + print(f"{len(tags)} labels") + + +if __name__ == "__main__": + main() diff --git a/workflows/token-classification/score.py b/workflows/token-classification/score.py new file mode 100644 index 0000000..16427c3 --- /dev/null +++ b/workflows/token-classification/score.py @@ -0,0 +1,61 @@ +"""Scores predicted entity spans against the gold spans, on a CPU, with the standard library only. + +An entity counts as found only when its type and its exact word span match a +gold entity (IOB2 tags: B- starts an entity, I- continues it). Prints precision, +recall and F1 overall and per entity type, and writes them to a JSON file. +""" + +import argparse +import json +from collections import Counter + + +def spans(tags): + """Returns the (type, start, end) of every entity in a sequence of IOB2 tags.""" + found, start, kind = [], None, None + for i, tag in enumerate(list(tags) + ["O"]): + prefix, _, entity = tag.partition("-") + if start is not None and (prefix != "I" or entity != kind): + found.append((kind, start, i)) + start = kind = None + if prefix == "B" or (prefix == "I" and start is None): + start, kind = i, entity + return found + + +def prf(tp, fp, fn): + precision = tp / (tp + fp) if tp + fp else 0.0 + recall = tp / (tp + fn) if tp + fn else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + return round(precision, 4), round(recall, 4), round(f1, 4) + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--predictions", required=True, help="JSON Lines file with gold and predicted tags per sentence") + p.add_argument("--output", required=True, help="JSON file the scores are written to") + args = p.parse_args() + + tp, fp, fn = Counter(), Counter(), Counter() + with open(args.predictions) as f: + for line in f: + row = json.loads(line) + gold, predicted = set(spans(row["gold"])), set(spans(row["predicted"])) + for kind, *_ in gold & predicted: + tp[kind] += 1 + for kind, *_ in predicted - gold: + fp[kind] += 1 + for kind, *_ in gold - predicted: + fn[kind] += 1 + + scores = {"overall": dict(zip(("precision", "recall", "f1"), prf(sum(tp.values()), sum(fp.values()), sum(fn.values()))))} + for kind in sorted(set(tp) | set(fn), key=lambda k: -(tp[k] + fn[k])): + scores[kind] = dict(zip(("precision", "recall", "f1"), prf(tp[kind], fp[kind], fn[kind])), entities=tp[kind] + fn[kind]) + with open(args.output, "w") as f: + json.dump(scores, f, indent=2) + for kind, score in scores.items(): + print(f"{kind:32} {score}") + + +if __name__ == "__main__": + main() diff --git a/workflows/token-classification/train.py b/workflows/token-classification/train.py new file mode 100644 index 0000000..5a9a9b4 --- /dev/null +++ b/workflows/token-classification/train.py @@ -0,0 +1,63 @@ +"""Fine-tunes a token-classification model on tokenized, tag-aligned splits, 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. +""" + +import argparse +import json + +from datasets import load_from_disk +from transformers import ( + AutoModelForTokenClassification, + AutoTokenizer, + DataCollatorForTokenClassification, + Trainer, + TrainingArguments, +) + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", required=True, help="Hub repo id or directory of the model to fine-tune") + p.add_argument("--data", required=True, help="Directory holding the tokenized splits and labels.json") + p.add_argument("--output", required=True, help="Directory the fine-tuned model is saved to") + p.add_argument("--epochs", type=float, default=3) + p.add_argument("--learning-rate", type=float, default=5e-5) + p.add_argument("--batch-size", type=int, default=16) + args = p.parse_args() + + with open(f"{args.data}/labels.json") as f: + labels = json.load(f) + tokenizer = AutoTokenizer.from_pretrained(args.model) + model = AutoModelForTokenClassification.from_pretrained( + args.model, + num_labels=len(labels), + id2label=dict(enumerate(labels)), + label2id={label: i for i, label in enumerate(labels)}, + ) + trainer = Trainer( + model=model, + args=TrainingArguments( + output_dir=f"{args.output}-checkpoints", + num_train_epochs=args.epochs, + learning_rate=args.learning_rate, + per_device_train_batch_size=args.batch_size, + per_device_eval_batch_size=args.batch_size, + eval_strategy="epoch", + save_strategy="no", + bf16=True, + dataloader_num_workers=2, + report_to="none", + ), + train_dataset=load_from_disk(f"{args.data}/train").remove_columns(["tokens"]), + eval_dataset=load_from_disk(f"{args.data}/eval").remove_columns(["tokens"]), + data_collator=DataCollatorForTokenClassification(tokenizer), + ) + trainer.train() + trainer.save_model(args.output) + tokenizer.save_pretrained(args.output) + + +if __name__ == "__main__": + main() diff --git a/workflows/token-classification/workflow.yaml b/workflows/token-classification/workflow.yaml new file mode 100644 index 0000000..34615a4 --- /dev/null +++ b/workflows/token-classification/workflow.yaml @@ -0,0 +1,147 @@ +name: Token classification +description: Fine-tunes an encoder model to tag named entities word by word, with tag alignment on a CPU, training and tagging on a GPU, and entity-level F1 computed on a CPU. +compute_type: cpu-4 + +inputs: + model: + description: Hub repo id of the encoder model to fine-tune; its tokenizer must accept text already split into words. + default: google-bert/bert-base-cased + train_data: + description: Parquet file or glob of training sentences, as a DuckDB path. + default: hf://datasets/adsabs/WIESP2022-NER/data/train-00000-of-00001.parquet + eval_data: + description: Parquet file or glob of evaluation sentences, as a DuckDB path. + default: hf://datasets/adsabs/WIESP2022-NER/data/validation-00000-of-00001.parquet + tokens_column: + description: Column holding each sentence as a list of words. + default: tokens + tags_column: + description: Column holding each sentence's IOB2 tags, one per word, as text such as B-Person. + default: ner_tags + epochs: + description: Training epochs. + default: "4" + examples_ref: + description: Branch, tag or full commit SHA of swaleio/examples whose scripts run. + default: main + hub_repo: + description: Hub 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 "${{inputs.tokens_column}}" AS tokens, "${{inputs.tags_column}}" AS tags FROM '${{inputs.train_data}}') + TO '${{env.WORKFLOW_STORAGE}}/train.parquet' (FORMAT parquet); + COPY (SELECT "${{inputs.tokens_column}}" AS tokens, "${{inputs.tags_column}}" AS tags FROM '${{inputs.eval_data}}') + TO '${{env.WORKFLOW_STORAGE}}/eval.parquet' (FORMAT parquet); + -- The most frequent entity types in the training split. + SELECT substr(tag, 3) AS entity, count(*) AS mentions + FROM (SELECT unnest(tags) AS tag FROM '${{env.WORKFLOW_STORAGE}}/train.parquet') + WHERE tag LIKE 'B-%' GROUP BY ALL ORDER BY mentions DESC LIMIT 15; + + tokenize: + name: Tokenize and align tags + 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-tokenize.txt"], check=True) + subprocess.run([sys.executable, f"{examples}/workflows/token-classification/preprocess.py", + "--model", f"{storage}/base-model", + "--train", f"{storage}/train.parquet", "--eval", f"{storage}/eval.parquet", + "--output", f"{storage}/tokenized"], + env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True) + + train: + name: Train + uses: swaleio/transformers + compute_type: a100-1 + start_on: + - tokenize + args: + script: | + import os, subprocess, sys + + storage = os.environ["WORKFLOW_STORAGE"] + subprocess.run([sys.executable, f"{storage}/examples/workflows/token-classification/train.py", + "--model", f"{storage}/base-model", "--data", f"{storage}/tokenized", + "--epochs", "${{inputs.epochs}}", "--output", f"{storage}/model"], check=True) + + predict: + name: Tag 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/token-classification/predict.py", + "--model", f"{storage}/model", "--data", f"{storage}/tokenized/eval", + "--output", f"{storage}/predictions.jsonl"], check=True) + + score: + name: Score entities + uses: swaleio/python-3-13 + start_on: + - predict + args: + script: | + import os, subprocess, sys + + storage = os.environ["WORKFLOW_STORAGE"] + subprocess.run([sys.executable, f"{storage}/examples/workflows/token-classification/score.py", + "--predictions", f"{storage}/predictions.jsonl", + "--output", f"{storage}/metrics.json"], check=True) + + publish: + name: Upload when asked + start_on: + - score + if: + condition: ${{inputs.hub_repo}} + true: upload + + upload: + tasks: + upload_model: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + source: ${{env.WORKFLOW_STORAGE}}/model + token: ${{secrets.hf_token}} diff --git a/workflows/train-then-serve/README.md b/workflows/train-then-serve/README.md new file mode 100644 index 0000000..053c71a --- /dev/null +++ b/workflows/train-then-serve/README.md @@ -0,0 +1,39 @@ +# Train then serve + +Fine-tunes a small chat model and serves it right away through vLLM's +OpenAI-compatible server, inside the same run. A smoke test waits for the +server, asks one question, and saves the answer; when it is done the platform +stops the server. Add your own consumers of the server, and list them in the +server's `terminate_on`. + +| Step | Task definition | Compute | +|------|-----------------|---------| +| Write the training config | `swaleio/bash` | `cpu-4` | +| Fine-tune | `swaleio/trl-sft` | `a100-1` | +| Write the smoke-test request | `swaleio/duckdb` | `cpu-4` | +| Serve the fine-tuned model, as a runner | `swaleio/vllm-serve` | `a100-1` | +| Wait for the server, checking every 5 seconds | `swaleio/http-request` | `cpu-4` | +| Ask the question | `swaleio/http-request` | `cpu-4` | + +Every step is its own task. + +## Inputs + +| Input | Default | Description | +|-------|---------|-------------| +| `model` | `Qwen/Qwen2.5-0.5B-Instruct` | Model to fine-tune. | +| `dataset` | `HuggingFaceH4/ultrafeedback_binarized` | Hub dataset with a `messages` column. | +| `split` | `train_sft[:5000]` | Split, or slice of one, to train on. | +| `question` | a question about fine-tuning | What the smoke test asks. | + +Training reads the secret `hf_token`. + +## Output + +The fine-tuned model in `model/` on the workspace, and the server's answer in +`answer.json`. + +## Licenses of the defaults + +- Model: [Qwen/Qwen2.5-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct), Apache-2.0. +- Training data: [HuggingFaceH4/ultrafeedback_binarized](https://huggingface.co/datasets/HuggingFaceH4/ultrafeedback_binarized), MIT. diff --git a/workflows/train-then-serve/workflow.yaml b/workflows/train-then-serve/workflow.yaml new file mode 100644 index 0000000..15f7fa5 --- /dev/null +++ b/workflows/train-then-serve/workflow.yaml @@ -0,0 +1,101 @@ +name: Train then serve +description: Fine-tunes a small chat model with TRL, serves the result through vLLM's OpenAI-compatible server, and checks it answers. +compute_type: cpu-4 + +inputs: + model: + description: Hub repo id of the model to fine-tune. + default: Qwen/Qwen2.5-0.5B-Instruct + dataset: + description: Hub dataset with a messages column of chat turns. + default: HuggingFaceH4/ultrafeedback_binarized + split: + description: Split of the dataset to train on. + default: train_sft[:5000] + question: + description: The question the smoke test asks the served model. + default: In one sentence, what is supervised fine-tuning? + +entry_point: main + +blocks: + main: + tasks: + write_config: + name: Write training config + uses: swaleio/bash + args: + script: | + cat > "$WORKFLOW_STORAGE/sft.yaml" < ${{inputs.eval_rows}}) + TO '${{env.WORKFLOW_STORAGE}}/train.parquet' (FORMAT parquet); + COPY (SELECT source, target FROM pairs WHERE n <= ${{inputs.eval_rows}}) + TO '${{env.WORKFLOW_STORAGE}}/eval.parquet' (FORMAT parquet); + SELECT (SELECT count(*) FROM '${{env.WORKFLOW_STORAGE}}/train.parquet') AS train_pairs, + (SELECT count(*) FROM '${{env.WORKFLOW_STORAGE}}/eval.parquet') AS eval_pairs; + + tokenize: + name: Tokenize + 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-tokenize.txt"], check=True) + subprocess.run([sys.executable, f"{examples}/workflows/summarization/preprocess.py", + "--model", f"{storage}/base-model", "--prefix", "${{inputs.prefix}}", + "--source-max-length", "256", "--target-max-length", "256", + "--train", f"{storage}/train.parquet", "--eval", f"{storage}/eval.parquet", + "--output", f"{storage}/tokenized"], + env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True) + + train: + name: Train + uses: swaleio/transformers + compute_type: a100-1 + start_on: + - tokenize + args: + script: | + import os, subprocess, sys + + storage = os.environ["WORKFLOW_STORAGE"] + subprocess.run([sys.executable, f"{storage}/examples/workflows/summarization/train.py", + "--model", f"{storage}/base-model", "--data", f"{storage}/tokenized", + "--epochs", "${{inputs.epochs}}", "--learning-rate", "2e-5", + "--output", f"{storage}/model"], check=True) + + generate: + name: Generate for 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/summarization/generate.py", + "--model", f"{storage}/model", "--eval", f"{storage}/eval.parquet", + "--prefix", "${{inputs.prefix}}", "--source-max-length", "256", + "--max-new-tokens", "256", "--output", f"{storage}/predictions.parquet"], check=True) + + score: + name: Score + uses: swaleio/python-3-13 + start_on: + - generate + 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-score-bleu.txt"], check=True) + subprocess.run([sys.executable, f"{examples}/workflows/summarization/score.py", + "--predictions", f"{storage}/predictions.parquet", "--metric", "bleu", + "--output", f"{storage}/metrics.json"], + env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True) + + publish: + name: Upload when asked + start_on: + - score + if: + condition: ${{inputs.hub_repo}} + true: upload + + upload: + tasks: + upload_model: + name: Upload to the Hub + uses: swaleio/hf-upload + args: + repo: ${{inputs.hub_repo}} + source: ${{env.WORKFLOW_STORAGE}}/model + token: ${{secrets.hf_token}} diff --git a/workflows/vlm-finetune/README.md b/workflows/vlm-finetune/README.md new file mode 100644 index 0000000..c3028e5 --- /dev/null +++ b/workflows/vlm-finetune/README.md @@ -0,0 +1,49 @@ +# Fine-tune a vision-language model + +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`](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` | + +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 | Hub 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. + +## 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). diff --git a/workflows/vlm-finetune/prepare.py b/workflows/vlm-finetune/prepare.py new file mode 100644 index 0000000..cff8f38 --- /dev/null +++ b/workflows/vlm-finetune/prepare.py @@ -0,0 +1,51 @@ +"""Turns a labelled image dataset into chat-format training rows for a vision-language model, on a CPU. + +Each row becomes a prompt, a user turn holding the image and a question, and a +completion, an assistant turn holding the answer: the image's label. With prompt +and completion columns, TRL's SFT trainer computes the loss on the answer alone; +over whole conversations, the image's many tokens drown the label out and the +model barely learns it. The images keep the Hugging Face Image type, so the +trainer receives them as images. +""" + +import argparse +import io + +import pyarrow as pa +import pyarrow.parquet as pq +from datasets import Features, Image, List, Value +from PIL import Image as PILImage + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--data", required=True, help="Parquet file with an image column (bytes) and a label column") + p.add_argument("--labels", required=True, help="Label names, separated by commas, in label-number order") + p.add_argument("--question", required=True, help="What the user asks about each image") + p.add_argument("--image-column", default="image") + p.add_argument("--label-column", default="labels") + p.add_argument("--output", required=True, help="Parquet file the chat rows are written to") + args = p.parse_args() + + labels = args.labels.split(",") + source = pq.read_table(args.data, columns=[args.image_column, args.label_column]).to_pylist() + rows = {"prompt": [], "completion": [], "images": []} + for row in source: + image = PILImage.open(io.BytesIO(row[args.image_column]["bytes"])).convert("RGB") + rows["images"].append([image]) + rows["prompt"].append([{"role": "user", "content": [{"type": "image", "text": None}, + {"type": "text", "text": args.question}]}]) + rows["completion"].append([{"role": "assistant", + "content": [{"type": "text", "text": labels[row[args.label_column]]}]}]) + content = List({"type": Value("string"), "text": Value("string")}) + turns = List({"role": Value("string"), "content": content}) + features = Features({"prompt": turns, "completion": turns, "images": List(Image())}) + # Written with PyArrow and the features' schema: building a datasets Dataset in memory + # fails with a MonthDayNano pickling error until the fix in + # https://github.com/huggingface/datasets/pull/8790 is released. + pq.write_table(pa.Table.from_pydict(features.encode_batch(rows), schema=features.arrow_schema), args.output) + print(f"wrote {len(rows['prompt'])} rows") + + +if __name__ == "__main__": + main() diff --git a/workflows/vlm-finetune/workflow.yaml b/workflows/vlm-finetune/workflow.yaml new file mode 100644 index 0000000..3b04066 --- /dev/null +++ b/workflows/vlm-finetune/workflow.yaml @@ -0,0 +1,198 @@ +name: Fine-tune a vision-language model +description: Fine-tunes a small vision-language model to answer a question about images with TRL, then has the base and the fine-tuned model answer held-out images through vLLM and compares their accuracy. +compute_type: cpu-4 + +inputs: + model: + description: Hub 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: Hub 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/vlm-finetune/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" <