Sync from GitHub via hub-sync
Browse files- README.md +101 -1
- train-kev.py +265 -0
README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
---
|
| 2 |
viewer: false
|
| 3 |
-
tags: [uv-script, classification, fine-tuning, few-shot, zero-shot, decision-model, setfit, gliner2, vllm, structured-outputs, hf-jobs]
|
| 4 |
---
|
| 5 |
|
| 6 |
# Classification Scripts
|
|
@@ -34,6 +34,7 @@ You need the `hf` CLI, signed in, and Jobs credit: see the [Jobs quickstart](htt
|
|
| 34 |
| [`train-gliner2.py`](#zero-shot-first-then-fine-tune-gliner2) | **Fine-tune** [GLiNER2](https://huggingface.co/fastino), a small model (74M–287M) that already classifies zero-shot, and report the zero-shot score next to the fine-tuned one |
|
| 35 |
| [`train-setfit.py`](#few-shot-with-setfit-train-setfitpy) | **Few-shot** train a classifier from 8-64 labels per class with [SetFit](https://huggingface.co/docs/setfit) — runs on CPU or GPU |
|
| 36 |
| [`train-classifier.py`](#fine-tune-a-classifier-train-classifierpy) | **Fine-tune** an encoder into a classifier (default: [LFM2.5-Encoder-350M](https://huggingface.co/LiquidAI/LFM2.5-Encoder-350M)) and push it to the Hub |
|
|
|
|
| 37 |
| [`classify-dataset.py`](#zero-shot-classification-classify-datasetpy) | **Zero-shot** classify a dataset with an instruction LLM (SmolLM3 + vLLM, structured outputs) |
|
| 38 |
| [`classify-dataset-sglang.py`](#zero-shot-classification-classify-datasetpy) | Zero-shot variant on SGLang (reasoning-aware `<think>` models) |
|
| 39 |
|
|
@@ -249,6 +250,105 @@ produces a plain, vLLM-servable model — pair it with
|
|
| 249 |
[`uv-scripts/vllm`](https://huggingface.co/datasets/uv-scripts/vllm)'s
|
| 250 |
`classify-dataset.py` for large-scale batch inference with the model you just trained.
|
| 251 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
## Zero-shot classification (`classify-dataset.py`)
|
| 253 |
|
| 254 |
Label a dataset with an instruction LLM and no training data. You give a list of labels; the
|
|
|
|
| 1 |
---
|
| 2 |
viewer: false
|
| 3 |
+
tags: [uv-script, classification, fine-tuning, few-shot, zero-shot, decision-model, setfit, gliner2, kev, vllm, structured-outputs, hf-jobs]
|
| 4 |
---
|
| 5 |
|
| 6 |
# Classification Scripts
|
|
|
|
| 34 |
| [`train-gliner2.py`](#zero-shot-first-then-fine-tune-gliner2) | **Fine-tune** [GLiNER2](https://huggingface.co/fastino), a small model (74M–287M) that already classifies zero-shot, and report the zero-shot score next to the fine-tuned one |
|
| 35 |
| [`train-setfit.py`](#few-shot-with-setfit-train-setfitpy) | **Few-shot** train a classifier from 8-64 labels per class with [SetFit](https://huggingface.co/docs/setfit) — runs on CPU or GPU |
|
| 36 |
| [`train-classifier.py`](#fine-tune-a-classifier-train-classifierpy) | **Fine-tune** an encoder into a classifier (default: [LFM2.5-Encoder-350M](https://huggingface.co/LiquidAI/LFM2.5-Encoder-350M)) and push it to the Hub |
|
| 37 |
+
| [`train-kev.py`](#fine-tune-a-kev-decision-model-train-kevpy) | **Fine-tune** the open [Kev-4B](https://huggingface.co/jaredpalmer/kev-4b) decision model on your own questions, with Kev's own training code |
|
| 38 |
| [`classify-dataset.py`](#zero-shot-classification-classify-datasetpy) | **Zero-shot** classify a dataset with an instruction LLM (SmolLM3 + vLLM, structured outputs) |
|
| 39 |
| [`classify-dataset-sglang.py`](#zero-shot-classification-classify-datasetpy) | Zero-shot variant on SGLang (reasoning-aware `<think>` models) |
|
| 40 |
|
|
|
|
| 250 |
[`uv-scripts/vllm`](https://huggingface.co/datasets/uv-scripts/vllm)'s
|
| 251 |
`classify-dataset.py` for large-scale batch inference with the model you just trained.
|
| 252 |
|
| 253 |
+
## Fine-tune a Kev decision model (`train-kev.py`)
|
| 254 |
+
|
| 255 |
+
[Kev](https://github.com/jaredpalmer/kev) is an open decision model by Jared Palmer. It answers
|
| 256 |
+
yes/no, multiple-choice and rating questions about a text, with a probability for each answer.
|
| 257 |
+
[Kev-4B](https://huggingface.co/jaredpalmer/kev-4b) is a rank-16 LoRA adapter and a small pointer
|
| 258 |
+
head on Qwen3.5-4B-Base. This script fine-tunes the released Kev-4B on your own labelled questions.
|
| 259 |
+
|
| 260 |
+
The script is a thin launcher. It pins one Kev commit and the Kev-4B v1.0 weights, installs Kev,
|
| 261 |
+
and runs Kev's own `kev.train`, `kev.benchmark` and `kev.calibrate`. All training and evaluation
|
| 262 |
+
code is Kev's. Kev's own recipes run on Modal (the `kev-finetune` skill) or on a GPU you have
|
| 263 |
+
([Fine-Tune on Your Own Data](https://github.com/jaredpalmer/kev#fine-tune-on-your-own-data));
|
| 264 |
+
use this script when your data and credit are already on the Hub.
|
| 265 |
+
|
| 266 |
+
First put `train.jsonl` and `development.jsonl` in a bucket folder (the snippet at the end of this
|
| 267 |
+
section shows one way). Each line is one record in Kev's format; a record can carry more than one
|
| 268 |
+
question:
|
| 269 |
+
|
| 270 |
+
```json
|
| 271 |
+
{"state": "<the text>",
|
| 272 |
+
"questions": {"newsgroup": {"type": "choice",
|
| 273 |
+
"instructions": "Which newsgroup was this post published in?",
|
| 274 |
+
"criteria": {"alt.atheism": null, "comp.graphics": null},
|
| 275 |
+
"label": "comp.graphics"}}}
|
| 276 |
+
```
|
| 277 |
+
|
| 278 |
+
Then run:
|
| 279 |
+
|
| 280 |
+
```bash
|
| 281 |
+
hf jobs uv run --flavor a100-large --timeout 1h --secrets HF_TOKEN \
|
| 282 |
+
-v hf://buckets/<you>/kev-data:/mnt/kev \
|
| 283 |
+
https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-kev.py \
|
| 284 |
+
/mnt/kev/newsgroups /mnt/kev/runs/newsgroups-v1
|
| 285 |
+
```
|
| 286 |
+
|
| 287 |
+
The script checks every record and the output folder before it installs anything. The output
|
| 288 |
+
folder must be new or empty. It gets `checkpoint/`, `finetuned-development/` and
|
| 289 |
+
`baseline-development/` (Kev benchmark reports for the fine-tuned and the released model),
|
| 290 |
+
`finetuned-development/calibration.json` (when `kev.calibrate` succeeds) and a `run.json` summary.
|
| 291 |
+
Each result is copied to the bucket as soon as it is written. On Jobs, the script refuses an output
|
| 292 |
+
folder that is not on a mounted bucket.
|
| 293 |
+
|
| 294 |
+
### Measured
|
| 295 |
+
|
| 296 |
+
| Task | Train / test records | Flavor | Time | Cost | Released Kev-4B | Fine-tuned |
|
| 297 |
+
|---|---|---|---|---|---|---|
|
| 298 |
+
| [`SetFit/20_newsgroups`](https://huggingface.co/datasets/SetFit/20_newsgroups) (20 classes) | 846 / 426 (1,000 / 500 prepared) | `a100-large` | 31 min | about $1.29 | 62.4% | 72.3% |
|
| 299 |
+
|
| 300 |
+
One seed, 2026-10-30. The paired difference is +9.9 points (95% CI +6.1 to +13.6). Training took
|
| 301 |
+
about 25 of the 31 minutes (846 records, 2 epochs).
|
| 302 |
+
|
| 303 |
+
**The fine-tuned model is overconfident**: mean confidence 0.82 against accuracy 0.72 (ECE 0.100).
|
| 304 |
+
The fine-tuned checkpoint runs at temperature 1.0. `calibration.json` reports what one temperature
|
| 305 |
+
fitted on your development records would do; nothing in the checkpoint changes. On 20 Newsgroups,
|
| 306 |
+
the out-of-fold fit (`workload_oof`) brings ECE to 0.028 and mean confidence to 0.73, with accuracy
|
| 307 |
+
unchanged (ECE change -0.072, 95% CI -0.092 to -0.023). To use the fitted value
|
| 308 |
+
(`workload_temperature`, 1.52 here), set `KEV_TEMPERATURE=1.52` when you serve or benchmark the
|
| 309 |
+
checkpoint with Kev's commands, or pass `LoadOptions(temperature=1.52)` when you load it in Python.
|
| 310 |
+
|
| 311 |
+
### Good to know
|
| 312 |
+
|
| 313 |
+
- **Long records are dropped.** `kev.train`'s default context is 384 state tokens (Kev's `--max_state`
|
| 314 |
+
raises it; this script does not expose it). `kev.train` drops longer records and prints how many; `kev.benchmark` drops them too and lists them in `rejected.json`. On
|
| 315 |
+
20 Newsgroups, after cutting posts at 2,000 characters, this dropped 154 of 1,000 training and 74 of
|
| 316 |
+
500 test posts.
|
| 317 |
+
- **Raise `--timeout` before you add data or epochs.** Training time grows with records × epochs.
|
| 318 |
+
If the Job hits the timeout, the results already copied stay in the bucket.
|
| 319 |
+
- **Everything is pinned:** the Kev commit, the Kev-4B weights (by commit, because a tag can move)
|
| 320 |
+
and the Qwen3.5 base revision. If the `kev-1.0` tag moves, the script stops with a message.
|
| 321 |
+
- **No extra kernels.** Kev's Modal images add `flash-linear-attention` (and, in `modal_app.py`,
|
| 322 |
+
`causal-conv1d`).
|
| 323 |
+
In our `a100-large` runs they gave no speed-up, so this script leaves them out.
|
| 324 |
+
- **Smoke test first:** `--max-steps 5` runs the whole path in about 6 minutes.
|
| 325 |
+
- **No 20 Newsgroups checkpoint is published.** `SetFit/20_newsgroups` declares no licence.
|
| 326 |
+
|
| 327 |
+
<details><summary>Turn a labelled dataset into Kev records (the 20 Newsgroups example)</summary>
|
| 328 |
+
|
| 329 |
+
```python
|
| 330 |
+
import json
|
| 331 |
+
from pathlib import Path
|
| 332 |
+
|
| 333 |
+
from datasets import load_dataset
|
| 334 |
+
|
| 335 |
+
data = load_dataset("SetFit/20_newsgroups")
|
| 336 |
+
labels = sorted(set(data["train"]["label_text"]))
|
| 337 |
+
out = Path("newsgroups")
|
| 338 |
+
out.mkdir(exist_ok=True)
|
| 339 |
+
for split, count, name in [("train", 1000, "train.jsonl"), ("test", 500, "development.jsonl")]:
|
| 340 |
+
rows = data[split].filter(lambda row: len(row["text"].strip()) >= 50).shuffle(seed=42).select(range(count))
|
| 341 |
+
with (out / name).open("w") as f:
|
| 342 |
+
for row in rows:
|
| 343 |
+
question = {"type": "choice", "instructions": "Which newsgroup was this post published in?",
|
| 344 |
+
"criteria": {label: None for label in labels}, "label": row["label_text"]}
|
| 345 |
+
f.write(json.dumps({"state": row["text"].strip()[:2000], "questions": {"newsgroup": question}}) + "\n")
|
| 346 |
+
```
|
| 347 |
+
|
| 348 |
+
Then copy the folder to your bucket: `hf buckets sync ./newsgroups hf://buckets/<you>/kev-data/newsgroups`.
|
| 349 |
+
|
| 350 |
+
</details>
|
| 351 |
+
|
| 352 |
## Zero-shot classification (`classify-dataset.py`)
|
| 353 |
|
| 354 |
Label a dataset with an instruction LLM and no training data. You give a list of labels; the
|
train-kev.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = []
|
| 4 |
+
#
|
| 5 |
+
# [tool.hf-jobs]
|
| 6 |
+
# flavor = "a100-large"
|
| 7 |
+
# timeout = "1h"
|
| 8 |
+
# secrets = ["HF_TOKEN"]
|
| 9 |
+
# ///
|
| 10 |
+
"""
|
| 11 |
+
Fine-tune a Kev decision model on your own labelled questions, on one HF Jobs GPU.
|
| 12 |
+
|
| 13 |
+
Kev (https://github.com/jaredpalmer/kev) answers yes/no, multiple-choice and rating questions
|
| 14 |
+
about a text, with a probability for each answer. This script is a thin launcher around Kev's
|
| 15 |
+
own commands. It pins one Kev commit and one set of released weights, installs Kev, and then runs:
|
| 16 |
+
|
| 17 |
+
1. `kev.train`: a LoRA + pointer-head delta from the released Kev-4B, on your training records.
|
| 18 |
+
2. `kev.benchmark`: the fine-tuned model and the released model, on your development records.
|
| 19 |
+
3. `kev.calibrate`: a calibration report for the fine-tuned model (report only, nothing changes).
|
| 20 |
+
|
| 21 |
+
All training and evaluation code is Kev's. Kev's own recipes run on Modal (the `kev-finetune`
|
| 22 |
+
skill) or on a GPU you have; this script is for people whose data and credit are on the Hub.
|
| 23 |
+
|
| 24 |
+
Input: a folder with `train.jsonl` and `development.jsonl` in Kev's record format (see the README).
|
| 25 |
+
Output: an empty or new folder on a mounted bucket. Each result is copied there as soon as it is
|
| 26 |
+
written: the checkpoint, both benchmark reports, the calibration report and `run.json`.
|
| 27 |
+
|
| 28 |
+
Example, with input and output in a bucket:
|
| 29 |
+
|
| 30 |
+
hf jobs uv run --flavor a100-large --timeout 1h --secrets HF_TOKEN \\
|
| 31 |
+
-v hf://buckets/<you>/kev-data:/mnt/kev \\
|
| 32 |
+
https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-kev.py \\
|
| 33 |
+
/mnt/kev/newsgroups /mnt/kev/runs/newsgroups-v1
|
| 34 |
+
|
| 35 |
+
Tested on 2026-10-30 (a100-large, 31 min, about $1.29): 20 Newsgroups, 846 training and 426 test
|
| 36 |
+
posts after Kev's length limit. Accuracy 72.3% fine-tuned vs 62.4% for the released Kev-4B. One seed.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
import argparse
|
| 40 |
+
import json
|
| 41 |
+
import os
|
| 42 |
+
import subprocess
|
| 43 |
+
import sys
|
| 44 |
+
import time
|
| 45 |
+
from pathlib import Path
|
| 46 |
+
|
| 47 |
+
KEV_REPO = "https://github.com/jaredpalmer/kev"
|
| 48 |
+
KEV_TAG = "kev-1.0"
|
| 49 |
+
KEV_COMMIT = "6b719c3c3f367295f6ef336f4f751cf5ff970abc" # the kev-1.0 tag on 2026-11-03
|
| 50 |
+
# jaredpalmer/kev-4b: the commit `@v1.0` resolved to on 2026-10-30 and 2026-11-03 (same weights as
|
| 51 |
+
# the v1.0 tag). Pinned by commit, because a tag can move.
|
| 52 |
+
INIT_MODEL = "jaredpalmer/kev-4b@6cfce5c2fa4b4bd64026336ab649c5ca78857d52"
|
| 53 |
+
BASE_MODEL = "Qwen/Qwen3.5-4B-Base"
|
| 54 |
+
BASE_REVISION = "1001bb4d826a52d1f399e183466143f4da7b741b" # main on 2026-11-03 (last change 2026-04-23)
|
| 55 |
+
QUESTION_TYPES = ("noul", "choice", "score")
|
| 56 |
+
MAX_OPTIONS = 255 # kev/api.py
|
| 57 |
+
WORK_DIR = Path("/tmp/kev")
|
| 58 |
+
SCRATCH = Path("/tmp/out")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def run(command, cwd=WORK_DIR):
|
| 62 |
+
print(f"\n$ {' '.join(command)}", flush=True)
|
| 63 |
+
started = time.time()
|
| 64 |
+
subprocess.run(command, cwd=cwd, check=True)
|
| 65 |
+
print(f"[{time.time() - started:.0f}s]", flush=True)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def check_gpu():
|
| 69 |
+
try:
|
| 70 |
+
listing = subprocess.run(["nvidia-smi", "-L"], capture_output=True, text=True)
|
| 71 |
+
except FileNotFoundError:
|
| 72 |
+
listing = None
|
| 73 |
+
if listing is None or listing.returncode != 0 or "GPU" not in listing.stdout:
|
| 74 |
+
sys.exit("No GPU found. Run this on a GPU flavor, for example --flavor a100-large.")
|
| 75 |
+
print(listing.stdout.strip(), flush=True)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def question_problem(question):
|
| 79 |
+
"""Why a labelled question is not in Kev's format, or None. Rules from kev/api.py and Kev's README:
|
| 80 |
+
noul labels are true/false; choice criteria is an object of options and the label is one of them;
|
| 81 |
+
score criteria is a list of levels and the label is a level's position from 0."""
|
| 82 |
+
if not isinstance(question, dict) or question.get("type") not in QUESTION_TYPES:
|
| 83 |
+
return f"needs a type: one of {', '.join(QUESTION_TYPES)}"
|
| 84 |
+
if "label" not in question:
|
| 85 |
+
return "needs a label"
|
| 86 |
+
kind, label, criteria = question["type"], question["label"], question.get("criteria")
|
| 87 |
+
if kind == "noul" and not isinstance(label, bool):
|
| 88 |
+
return "is a noul question, so its label must be true or false"
|
| 89 |
+
if kind == "choice":
|
| 90 |
+
if not isinstance(criteria, dict) or not 1 <= len(criteria) <= MAX_OPTIONS:
|
| 91 |
+
return f"is a choice question, so its criteria must be an object with 1 to {MAX_OPTIONS} options"
|
| 92 |
+
if label not in criteria:
|
| 93 |
+
return f"has label {label!r}, which is not one of its criteria"
|
| 94 |
+
if kind == "score":
|
| 95 |
+
if not isinstance(criteria, list) or not 1 <= len(criteria) <= MAX_OPTIONS:
|
| 96 |
+
return f"is a score question, so its criteria must be a list of 1 to {MAX_OPTIONS} levels"
|
| 97 |
+
if isinstance(label, bool) or not isinstance(label, int) or not 0 <= label < len(criteria):
|
| 98 |
+
return f"is a score question, so its label must be a level position from 0 to {len(criteria) - 1}"
|
| 99 |
+
return None
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def check_records(path):
|
| 103 |
+
"""Fail before any GPU time is spent if a record is not in Kev's labelled format."""
|
| 104 |
+
if not path.is_file():
|
| 105 |
+
sys.exit(f"{path} not found. The input folder needs train.jsonl and development.jsonl.")
|
| 106 |
+
count = 0
|
| 107 |
+
with path.open() as f:
|
| 108 |
+
for line_number, line in enumerate(f, start=1):
|
| 109 |
+
if not line.strip():
|
| 110 |
+
continue
|
| 111 |
+
where = f"{path.name} line {line_number}"
|
| 112 |
+
try:
|
| 113 |
+
record = json.loads(line)
|
| 114 |
+
except json.JSONDecodeError as error:
|
| 115 |
+
sys.exit(f"{where}: not valid JSON ({error}).")
|
| 116 |
+
if not isinstance(record, dict) or record.get("state") is None:
|
| 117 |
+
sys.exit(f'{where}: a record needs a "state" (text, or any JSON object or list).')
|
| 118 |
+
questions = record.get("questions")
|
| 119 |
+
if not isinstance(questions, dict) or not questions:
|
| 120 |
+
sys.exit(f'{where}: a record needs a non-empty "questions" object.')
|
| 121 |
+
for name, question in questions.items():
|
| 122 |
+
problem = question_problem(question)
|
| 123 |
+
if problem:
|
| 124 |
+
sys.exit(f'{where}: question "{name}" {problem}.')
|
| 125 |
+
count += 1
|
| 126 |
+
if count == 0:
|
| 127 |
+
sys.exit(f"{path} has no records.")
|
| 128 |
+
print(f"{path.name}: {count} records", flush=True)
|
| 129 |
+
return count
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def mount_of(path, mounts_file=Path("/proc/self/mounts")):
|
| 133 |
+
"""(mount point, filesystem type, device) of the mount that holds `path`."""
|
| 134 |
+
best = ("", "", "")
|
| 135 |
+
for line in mounts_file.read_text().splitlines():
|
| 136 |
+
device, mount_point, fstype = line.split()[:3]
|
| 137 |
+
holds_path = path == Path(mount_point) or Path(mount_point) in path.parents
|
| 138 |
+
if holds_path and len(mount_point) > len(best[0]):
|
| 139 |
+
best = (mount_point, fstype, device)
|
| 140 |
+
return best
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def prepare_output(output_dir):
|
| 144 |
+
"""Fail before any GPU time is spent if the results would be lost or mixed with an old run."""
|
| 145 |
+
if os.environ.get("JOB_ID"):
|
| 146 |
+
# on Jobs, only a mounted bucket outlives the container (it shows as device "hf-mount")
|
| 147 |
+
mount_point, fstype, device = mount_of(output_dir)
|
| 148 |
+
if device != "hf-mount":
|
| 149 |
+
sys.exit(f"{output_dir} is not on a mounted bucket (it is on {mount_point}, {fstype or 'unknown'}). "
|
| 150 |
+
"Mount one with -v hf://buckets/<you>/<bucket>:/mnt/kev and write under /mnt/kev.")
|
| 151 |
+
if output_dir.exists() and any(output_dir.iterdir()):
|
| 152 |
+
sys.exit(f"{output_dir} is not empty. Use a new folder for each run.")
|
| 153 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 154 |
+
(output_dir / "run.json").write_text(json.dumps({"status": "started"})) # also checks that the folder is writable
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def install_kev():
|
| 158 |
+
run(["git", "clone", "-q", "--depth", "1", "--branch", KEV_TAG, KEV_REPO, str(WORK_DIR)], cwd="/tmp")
|
| 159 |
+
head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=WORK_DIR, check=True, capture_output=True, text=True)
|
| 160 |
+
if head.stdout.strip() != KEV_COMMIT:
|
| 161 |
+
sys.exit(f"{KEV_TAG} now points to {head.stdout.strip()}, not {KEV_COMMIT}. Check the Kev release notes.")
|
| 162 |
+
run(["uv", "sync", "--no-dev", "-q"])
|
| 163 |
+
cuda = subprocess.run(["uv", "run", "python", "-c", "import torch; print(torch.cuda.is_available())"],
|
| 164 |
+
cwd=WORK_DIR, capture_output=True, text=True)
|
| 165 |
+
if cuda.stdout.strip() != "True":
|
| 166 |
+
sys.exit(f"PyTorch in Kev's environment cannot use the GPU.\n{cuda.stderr[-2000:]}")
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def save(name, output_dir):
|
| 170 |
+
"""Copy one finished result to the output folder, so a later failure cannot lose it."""
|
| 171 |
+
destination = output_dir / name
|
| 172 |
+
destination.mkdir(parents=True, exist_ok=True)
|
| 173 |
+
subprocess.run(["cp", "-r", f"{SCRATCH / name}/.", str(destination)], check=True)
|
| 174 |
+
print(f"saved {destination}", flush=True)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def train(args):
|
| 178 |
+
command = [
|
| 179 |
+
"uv", "run", "python", "-m", "kev.train",
|
| 180 |
+
"--data", str(args.input_dir / "train.jsonl"),
|
| 181 |
+
"--base", BASE_MODEL,
|
| 182 |
+
"--base_revision", BASE_REVISION,
|
| 183 |
+
"--init_from", args.init_from,
|
| 184 |
+
"--epochs", str(args.epochs),
|
| 185 |
+
"--lr", str(args.lr),
|
| 186 |
+
"--batch", "1", "--accum", "8", "--dtype", "bf16", "--checkpointing", "1",
|
| 187 |
+
"--device", "cuda",
|
| 188 |
+
"--out", str(SCRATCH / "checkpoint"),
|
| 189 |
+
]
|
| 190 |
+
if args.max_steps:
|
| 191 |
+
command += ["--max_steps", str(args.max_steps)]
|
| 192 |
+
run(command)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def benchmark(model, data, name):
|
| 196 |
+
run(["uv", "run", "python", "-m", "kev.benchmark", "--run", str(model), "--data", str(data), "--out", str(SCRATCH / name)])
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def calibrate():
|
| 200 |
+
"""Kev's calibration report. It needs enough development records for its folds, so a failure
|
| 201 |
+
here is reported and the run goes on: the checkpoint and benchmarks are already saved."""
|
| 202 |
+
try:
|
| 203 |
+
run(["uv", "run", "python", "-m", "kev.calibrate", "--rows", str(SCRATCH / "finetuned-development" / "rows.json")])
|
| 204 |
+
report = json.loads((SCRATCH / "finetuned-development" / "calibration.json").read_text())
|
| 205 |
+
except (subprocess.CalledProcessError, OSError, json.JSONDecodeError) as error:
|
| 206 |
+
print(f"kev.calibrate failed ({error}); see the messages above. The other results are saved.", flush=True)
|
| 207 |
+
return None
|
| 208 |
+
return report.get("workload_temperature")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def headline(name):
|
| 212 |
+
clean = json.loads((SCRATCH / name / "report.json").read_text())["clean"]
|
| 213 |
+
return {"n": clean["n"], "acc": round(clean["acc"], 4), "ece": round(clean["ece"], 4)}
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def main():
|
| 217 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 218 |
+
parser.add_argument("input_dir", type=Path, help="Folder with train.jsonl and development.jsonl in Kev's format")
|
| 219 |
+
parser.add_argument("output_dir", type=Path, help="New or empty folder for the results, on a mounted bucket")
|
| 220 |
+
parser.add_argument("--init-from", default=INIT_MODEL, help="Released Kev model to start from (repo@revision)")
|
| 221 |
+
parser.add_argument("--epochs", type=int, default=2)
|
| 222 |
+
parser.add_argument("--lr", type=float, default=2e-5)
|
| 223 |
+
parser.add_argument("--max-steps", type=int, default=0, help="Stop after this many optimizer steps, for a smoke test")
|
| 224 |
+
args = parser.parse_args()
|
| 225 |
+
# Kev's commands run from its own checkout, so relative paths must not reach them
|
| 226 |
+
args.input_dir = args.input_dir.resolve()
|
| 227 |
+
args.output_dir = args.output_dir.resolve()
|
| 228 |
+
|
| 229 |
+
check_gpu()
|
| 230 |
+
check_records(args.input_dir / "train.jsonl")
|
| 231 |
+
check_records(args.input_dir / "development.jsonl")
|
| 232 |
+
prepare_output(args.output_dir)
|
| 233 |
+
started = time.time()
|
| 234 |
+
install_kev()
|
| 235 |
+
|
| 236 |
+
development = args.input_dir / "development.jsonl"
|
| 237 |
+
train(args)
|
| 238 |
+
save("checkpoint", args.output_dir)
|
| 239 |
+
benchmark(SCRATCH / "checkpoint", development, "finetuned-development")
|
| 240 |
+
save("finetuned-development", args.output_dir)
|
| 241 |
+
benchmark(args.init_from, development, "baseline-development")
|
| 242 |
+
save("baseline-development", args.output_dir)
|
| 243 |
+
temperature = calibrate()
|
| 244 |
+
if temperature is not None:
|
| 245 |
+
# copy only the new file: the saved reports stay as they are
|
| 246 |
+
calibration = SCRATCH / "finetuned-development" / "calibration.json"
|
| 247 |
+
subprocess.run(["cp", str(calibration), str(args.output_dir / "finetuned-development")], check=True)
|
| 248 |
+
print(f"saved {args.output_dir / 'finetuned-development' / 'calibration.json'}", flush=True)
|
| 249 |
+
|
| 250 |
+
summary = {
|
| 251 |
+
"status": "completed",
|
| 252 |
+
"kev_commit": KEV_COMMIT,
|
| 253 |
+
"init_from": args.init_from,
|
| 254 |
+
"base_revision": BASE_REVISION,
|
| 255 |
+
"finetuned": headline("finetuned-development"),
|
| 256 |
+
"released": headline("baseline-development"),
|
| 257 |
+
"workload_temperature": temperature,
|
| 258 |
+
"seconds": round(time.time() - started),
|
| 259 |
+
}
|
| 260 |
+
(args.output_dir / "run.json").write_text(json.dumps(summary, indent=2))
|
| 261 |
+
print(json.dumps(summary), flush=True)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
if __name__ == "__main__":
|
| 265 |
+
main()
|