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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GLiNER2 scripts: tested runs, findings and dead ends
|
| 2 |
+
|
| 3 |
+
Notes behind `train-gliner2.py` and `classify-gliner2.py`. The README has what you need to run them;
|
| 4 |
+
this file records what was tried, what worked, what did not, and the exact runs the README numbers
|
| 5 |
+
come from. Much of it was run and written up by coding agents (Claude) and checked by a person.
|
| 6 |
+
|
| 7 |
+
## Tested commands
|
| 8 |
+
|
| 9 |
+
Each README command was run from the branch before merge (`t4-small`, 2026-09-23):
|
| 10 |
+
|
| 11 |
+
| Command | Result | Time | Cost |
|
| 12 |
+
|---|---|---|---|
|
| 13 |
+
| train, `biglam/blbooksgenre` `title_genre_classifiction`, defaults | zero-shot 0.793 → fine-tuned 0.925 (174-row carve-out) | 149 s training | ~$0.02 |
|
| 14 |
+
| classify with that model, same dataset | 1,736 rows labelled | 20 s | <$0.01 |
|
| 15 |
+
| classify zero-shot, `fancyzhx/ag_news` test, 4 labels | 7,600 rows labelled | 96 s | ~$0.02 |
|
| 16 |
+
| train, `fancyzhx/ag_news`, `--max-train-samples 2000 --epochs 2` | 0.733 → 0.873 (2,000 test rows) | 137 s training, 298 s whole Job | ~$0.03 |
|
| 17 |
+
|
| 18 |
+
The ag_news README row (0.718 → 0.852) and this run (0.733 → 0.873) differ because the 2,000
|
| 19 |
+
scored test rows are a different random sample. Expect roughly 0.72 → 0.85–0.87.
|
| 20 |
+
|
| 21 |
+
## Larger or fixed label sets
|
| 22 |
+
|
| 23 |
+
For tens of labels that are always scored together (a taxonomy, a fixed tag list), and for data
|
| 24 |
+
you keep in a bucket instead of a Hub dataset:
|
| 25 |
+
|
| 26 |
+
```bash
|
| 27 |
+
hf jobs uv run --flavor a10g-small --timeout 2h --secrets HF_TOKEN \
|
| 28 |
+
-v hf://buckets/username/my-bucket:/bucket \
|
| 29 |
+
https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-gliner2.py \
|
| 30 |
+
--train-file /bucket/train.jsonl \
|
| 31 |
+
--eval-file calibration=/bucket/calibration.jsonl --eval-file development=/bucket/development.jsonl \
|
| 32 |
+
--labels-file /bucket/labels.json --label-column labels --label-augmentation off \
|
| 33 |
+
--base-model fastino/gliner2.5-base-v1 \
|
| 34 |
+
--no-push --output-dir /bucket/runs/gliner2 --export-predictions /bucket/runs/gliner2/predictions
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
- `--labels-file` fixes the label set and its order for training, zero-shot and evaluation, so a
|
| 38 |
+
label that is rare or missing in the training data is still an option.
|
| 39 |
+
- `--label-augmentation off`: gliner2's trainer by default renames labels to "label 1", "label 2",
|
| 40 |
+
… in half the rows and drops up to half of them, which helps a general zero-shot model. With a
|
| 41 |
+
fixed label set it cost 2–3 points of top-1 on the 52-tag example.
|
| 42 |
+
- `--eval-file NAME=PATH` (repeatable) scores each split in full and in file order.
|
| 43 |
+
- `--export-predictions` writes every row's probability and raw logit for every label, so you can
|
| 44 |
+
fit your own temperature or thresholds on one split and check them on another.
|
| 45 |
+
- `--no-push` keeps the model in `--output-dir` instead of creating a Hub repo.
|
| 46 |
+
|
| 47 |
+
## Measured table notes
|
| 48 |
+
|
| 49 |
+
On the T4, TREC and IMDB ran out of memory at the default batch size of 16, and the script restarted
|
| 50 |
+
them at batch size 4 with 4 gradient accumulation steps. Before that fallback existed, the TREC run
|
| 51 |
+
"completed" with 1,006 of 1,020 steps skipped and scored 0.576 / 0.484, barely above zero-shot. Many
|
| 52 |
+
labels are also slow: TREC trained at 9 rows/s against 55 rows/s for the 2-label task, because every
|
| 53 |
+
label is part of the input. For hundreds of labels, use `train-classifier.py`. Prediction was not the
|
| 54 |
+
limit: the 300 IMDB reviews were scored at batch size 32 on the T4 with no fallback.
|
| 55 |
+
|
| 56 |
+
The same BL books run (seed 42) scored 0.925 on a T4, 0.937 on an A10G in fp32 and 0.931 on an A10G in
|
| 57 |
+
bf16 — one or two eval rows apart, so hardware and precision are not a way to gain accuracy, but they
|
| 58 |
+
are one more thing to hold constant when you compare runs.
|
| 59 |
+
|
| 60 |
+
Two upstream options are deliberately absent: in `gliner2` 2.0.0, gradient checkpointing crashes
|
| 61 |
+
with the 2.5 models, and a LoRA run trained but its final checkpoint did not load for scoring (LoRA
|
| 62 |
+
also did not fix the 56-label out-of-memory case on a T4).
|
| 63 |
+
|
| 64 |
+
The BL books row is the mean and range of five seeds; the other rows are one seed each. Read the
|
| 65 |
+
range before you compare two runs: `--seed` also picks the carve-out rows, and the zero-shot model
|
| 66 |
+
never changes, so its 3-point spread is what 174 eval rows do to the number on their own. A
|
| 67 |
+
difference smaller than that between two runs is not a result. Use a dataset with a fixed
|
| 68 |
+
`--eval-split`, and as many eval rows as you can get, when you want to compare runs.
|
| 69 |
+
|
| 70 |
+
The ag_news, go_emotions and TREC rows are deliberately small runs (capped training rows, 2–3 epochs) that
|
| 71 |
+
test the script, not tuned results. The BL books row trains on the full 1,562 titles; its eval is a 10%
|
| 72 |
+
carve-out, so it is not comparable with published numbers for that dataset.
|
| 73 |
+
|
| 74 |
+
## A larger label set: 52 Hub task tags
|
| 75 |
+
|
| 76 |
+
`train-gliner2.py` was used to fine-tune a tagger that suggests a Hub dataset's task tags from its
|
| 77 |
+
column names and first row (the worked example in the README).
|
| 78 |
+
|
| 79 |
+
- 16,000 training datasets, 1,000 calibration and 3,000 development datasets; calibration and
|
| 80 |
+
development are newer datasets from owners not in the training data.
|
| 81 |
+
- `gliner2.5-base-v1`, `--labels-file` (52 tags), multi-label, `--label-augmentation off`, 5 epochs,
|
| 82 |
+
`rtx-pro-6000`, about 17 minutes of training.
|
| 83 |
+
- Development top-1 in the owner's tags: base 0.695 / 0.686 (two seeds), small 0.653, zero-shot
|
| 84 |
+
0.102. Always answering "text-generation" scores 0.320, so zero-shot is below a constant guess.
|
| 85 |
+
- `--label-augmentation upstream` (gliner2's default) scored 0.664: turning it off added 2–3 points.
|
| 86 |
+
- The two seeds differ by about 1 point, almost all of it on one owner's 33 near-identical
|
| 87 |
+
datasets that the model labels tabular-regression or tabular-classification depending on the seed.
|
| 88 |
+
- Owner tags are noisy: in a hand-checked sample, about 1 in 10 datasets was missing a tag that fits.
|
| 89 |
+
|
| 90 |
+
How it was set up, if you want to do something similar with your own label list:
|
| 91 |
+
|
| 92 |
+
- **Input text:** the dataset's column names and types, then its first row, built from the dataset
|
| 93 |
+
viewer's preview and cut to about 370 tokens. Keep the exact same builder for training and
|
| 94 |
+
prediction; a small difference in the text is a different input.
|
| 95 |
+
- **Labels:** a fixed `--labels-file` of 52 tags, multi-label (`labels` is a list per row), with
|
| 96 |
+
`--label-augmentation off`.
|
| 97 |
+
- **Split by time and owner:** the evaluation rows are newer datasets from owners who are not in
|
| 98 |
+
the training data, so the score is not inflated by near-duplicate datasets from the same owner.
|
| 99 |
+
- **Two eval files** (`--eval-file calibration=… --eval-file development=…`) and
|
| 100 |
+
`--export-predictions`: thresholds are chosen on one file and checked on the other.
|
| 101 |
+
|
| 102 |
+
## Speed and quantization
|
| 103 |
+
|
| 104 |
+
Per-row latency at batch size 1, fine-tuned 52-label models:
|
| 105 |
+
|
| 106 |
+
| Model | L4 (fp16) | T4 (fp16) | Apple M1 Pro CPU | Free CPU Space (2 vCPU) |
|
| 107 |
+
|---|---|---|---|---|
|
| 108 |
+
| gliner2.5-small | ~19 ms | — | — | ~0.3 s |
|
| 109 |
+
| gliner2.5-base | ~19 ms | ~27 ms | ~0.19 s | ~0.7–1 s |
|
| 110 |
+
|
| 111 |
+
- On a GPU, small and base take the same time per row; fixed overhead dominates.
|
| 112 |
+
- **Dynamic int8 did not work.** Agreement of the top label with fp32 on 64 rows: ONNX Runtime
|
| 113 |
+
default 6%, `torch.ao` Linear 1.6%, per-channel 58%, MatMul-only per-channel 59%, skipping the
|
| 114 |
+
feed-forward down-projection 91%, attention layers only 94%. Speed-up was at most 1.2×. The fp32
|
| 115 |
+
margins between the top two labels were healthy, so activation outliers in the fine-tuned
|
| 116 |
+
encoder are the likely cause. Calibrated static int8, or keeping sensitive layers in full
|
| 117 |
+
precision, might work; it was not tried.
|
| 118 |
+
- **ONNX:** `gliner2` 2.0.0 has no export. Exporting only the encoder matches fp32 exactly, but
|
| 119 |
+
ran 1.8× slower than PyTorch on an Apple M1.
|
| 120 |
+
- bf16 on a CPU keeps the same answers but was 6× slower on an M1.
|
| 121 |
+
- On HF CPU Jobs, `os.cpu_count()` reports the host's cores, not the Job's vCPUs. Set torch's
|
| 122 |
+
thread count explicitly or the run oversubscribes and stalls.
|
| 123 |
+
|
| 124 |
+
## Behaviour details
|
| 125 |
+
|
| 126 |
+
- **Single-label and multi-label**, auto-detected from the label column (a list per row is multi-label). An empty list is kept as a valid "none of these" answer.
|
| 127 |
+
- **Several tasks in one model.** Repeat `--label-column` and each column becomes a task; the model answers all of them in one pass. `classify-gliner2.py` then writes one `predicted_<task>` and one `predicted_<task>_confidence` column per task.
|
| 128 |
+
- **Evaluation split and metrics match `train-classifier.py` and `train-setfit.py`** (`--eval-split`, else `validation`, else `test`, else a carve-out; accuracy + macro F1), so the rungs are comparable. Multi-label tasks report micro/macro F1 and exact match.
|
| 129 |
+
- **Label names are part of the prompt.** Real names (`Fiction`, `Sports`) work; integer codes make zero-shot meaningless, and the script warns. Brackets are stripped from label names because GLiNER2 rejects them at inference.
|
| 130 |
+
- **It does not train on nothing.** The GLiNER2 trainer catches a CUDA out-of-memory error, skips the batch and carries on, so an undersized GPU looks like a healthy job that produces an untrained model. After 5 out-of-memory steps the script restarts itself at a quarter of the batch size, with 4× the gradient accumulation, so the effective batch size stays the same. It goes down to batch size 1, then stops before anything is pushed. The model card's reproduce command records the batch size that worked. Memory grows with batch size × number of labels × text length.
|
| 131 |
+
- **The launch config ships with the script.** Both scripts carry a [`[tool.hf-jobs]` header](https://huggingface.co/docs/hub/jobs-configuration#define-the-launch-config-in-the-script) (`t4-small`, a 1 hour timeout, the `HF_TOKEN` secret). With `hf` CLI 1.32 or newer, `hf jobs uv run <script-url> <args>` is enough, and `--dry-run` shows what it resolves to. Flags still win, and the examples here keep them so they also work on older CLIs — which ignore the header and stop the Job after 30 minutes, before the model is pushed. Pass `--timeout` explicitly (the examples use `1h`; a large run needs more) whenever you cannot be sure which CLI launches the job.
|
| 132 |
+
- **Outputs are private by default.** `train-gliner2.py` creates a private model repo and `classify-gliner2.py` a private dataset; pass `--public` to opt out. If the target repo already exists and is public, both scripts stop before doing any work. (`--private` is still accepted, and does nothing.)
|
| 133 |
+
- **Local files, several eval splits, exported predictions.** Instead of a Hub dataset, `train-gliner2.py` can read JSON Lines files, for example from a bucket mounted with `-v`:
|
| 134 |
+
|
| 135 |
+
```bash
|
| 136 |
+
hf jobs uv run --flavor a10g-small --timeout 2h --secrets HF_TOKEN \
|
| 137 |
+
-v hf://buckets/username/my-bucket:/bucket \
|
| 138 |
+
https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-gliner2.py \
|
| 139 |
+
--train-file /bucket/train.jsonl \
|
| 140 |
+
--eval-file calibration=/bucket/calibration.jsonl --eval-file development=/bucket/development.jsonl \
|
| 141 |
+
--labels-file /bucket/labels.json --label-column labels --label-augmentation off \
|
| 142 |
+
--no-push --output-dir /bucket/runs/gliner2 --export-predictions /bucket/runs/gliner2/predictions
|
| 143 |
+
```
|
| 144 |
+
|
| 145 |
+
- `--eval-file NAME=PATH` (repeatable): each file is an eval split, scored zero-shot and fine-tuned, in full and in file order.
|
| 146 |
+
- `--labels-file`: a JSON list or one label per line. It fixes the label set and its order for training, zero-shot and evaluation; a label in the data that is not in the file stops the run.
|
| 147 |
+
- `--export-predictions DIR`: writes `DIR/{base,finetuned}-<split>/predictions.jsonl`, one line per row: `{"row": i, "probabilities": {task: {label: p}}, "logits": {task: {label: logit}}}` with every label. Probabilities are gliner2's (softmax for a single-label task, a sigmoid per label for multi-label); logits are the raw per-label scores. Exporting also switches off the `--max-eval-samples` cap for a Hub eval split.
|
| 148 |
+
- `--no-push`: no Hub repo is created or written; the model stays in `--output-dir/final`.
|
| 149 |
+
- `--label-augmentation off`: gliner2's trainer by default renames the labels to "label 1", "label 2", ... in half of the training rows and drops up to half of the labels (`upstream`). With a fixed label set that is always scored in full, `off` trains on the real, complete label set every time; label-order shuffling stays on.
|
| 150 |
+
- A `run_manifest.json` (all arguments except the token, the label-augmentation config, precision, device and package versions, then the results) is written to `--output-dir`, the export directory and the model folder.
|
| 151 |
+
- **Pick the GPU by label count and text length.** A `t4-small` fit short texts with 2, 4 and 28 labels at the default batch size. The 56-label TREC task and 2,000-character IMDB reviews both fell back to batch size 4, and IMDB did so on the A10G too. `a10g-small` (24 GB) trains about 2.3× faster and fit the 56-label TREC run at the default batch size, in 509s against 1,761s on the T4 at batch size 4. `--precision auto` uses bf16 on Ampere or newer GPUs (A10G, L4) and fp32 on a T4; on the A10G bf16 and fp32 ran at the same speed (62s and 59s), so bf16 there buys memory, not time.
|
| 152 |
+
- **Texts are truncated** to `--max-text-chars` (default 2000), with a count.
|
| 153 |
+
- **It is a GLiNER2 checkpoint**, loaded with `gliner2.classification.Classifier.from_pretrained(repo)`, not `AutoModelForSequenceClassification`. `gliner2` pins `transformers<5`, which keeps `huggingface_hub` below 1.0 inside the Job. The `hf` CLI 1.32 or newer that reads the `[tool.hf-jobs]` header is a separate install on your own machine, so the two versions do not conflict.
|
| 154 |
+
|
| 155 |
+
## Dead ends
|
| 156 |
+
|
| 157 |
+
- Gradient checkpointing crashes with the GLiNER2.5 models in `gliner2` 2.0.0.
|
| 158 |
+
- A LoRA run trained, but its final checkpoint did not load for scoring, and LoRA did not fix the
|
| 159 |
+
56-label out-of-memory case on a T4.
|
| 160 |
+
- Before the out-of-memory restart existed, a TREC run "completed" with 1,006 of 1,020 steps
|
| 161 |
+
skipped and scored barely above zero-shot. Check the logs for `OOM at step` when a result looks flat.
|
README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
---
|
| 2 |
viewer: false
|
| 3 |
-
tags: [uv-script, classification, fine-tuning, few-shot, setfit, vllm, structured-outputs, hf-jobs]
|
| 4 |
---
|
| 5 |
|
| 6 |
# Classification Scripts
|
|
@@ -9,8 +9,10 @@ Text classification on [HF Jobs](https://huggingface.co/docs/huggingface_hub/gui
|
|
| 9 |
|
| 10 |
| Script | What it does |
|
| 11 |
|--------|--------------|
|
| 12 |
-
| [`
|
|
|
|
| 13 |
| [`train-setfit.py`](#few-shot-with-setfit-train-setfitpy) | **Few-shot** train a classifier from 8-64 labels per class with [SetFit](https://github.com/huggingface/setfit) — runs on CPU or GPU |
|
|
|
|
| 14 |
| [`classify-dataset.py`](#zero-shot-classification-classify-datasetpy) | **Zero-shot** classify a dataset with an instruction LLM (SmolLM3 + vLLM, structured outputs) |
|
| 15 |
| `classify-dataset-sglang.py` | Zero-shot variant on SGLang (reasoning-aware `<think>` models) |
|
| 16 |
|
|
@@ -18,64 +20,118 @@ Pick by how many labels you have:
|
|
| 18 |
|
| 19 |
| Labels you have | Use | Hardware |
|
| 20 |
|---|---|---|
|
| 21 |
-
| none | `classify-
|
| 22 |
| ~8-64 per class | `train-setfit.py` | CPU supported; GPU for faster training |
|
| 23 |
-
| a few thousand | `train-
|
|
|
|
| 24 |
|
| 25 |
The rungs chain: bootstrap labels with `classify-dataset.py`, review them, then train a small
|
| 26 |
dedicated model on what you kept.
|
| 27 |
|
| 28 |
-
##
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
|
|
|
| 32 |
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
| 36 |
|
| 37 |
-
``
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
-
#
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
```
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
validation/test, or holds out 10% of train). Run `uv run train-classifier.py --help` for all.
|
| 53 |
|
| 54 |
-
|
|
|
|
|
|
|
| 55 |
|
| 56 |
-
|
| 57 |
-
contains 21k Hub dataset cards (frontmatter stripped) labelled with their `task_categories`
|
| 58 |
-
metadata — a real multi-label task over long documents:
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
``
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
| 69 |
|
| 70 |
-
###
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
`
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
## Few-shot with SetFit (`train-setfit.py`)
|
| 78 |
|
|
|
|
|
|
|
| 79 |
Trains a [SetFit](https://github.com/huggingface/setfit) classifier from a handful of labelled
|
| 80 |
examples per class. SetFit finetunes a sentence-transformer body on contrastive pairs, then fits a
|
| 81 |
logistic regression head on the resulting embeddings.
|
|
@@ -191,6 +247,55 @@ it suggests undersampling where applicable and estimates whether that would fit
|
|
| 191 |
> **Note**: a SetFit model is a sentence-transformer body plus a scikit-learn head. Load it with
|
| 192 |
> `SetFitModel.from_pretrained(repo)`, not `AutoModelForSequenceClassification`.
|
| 193 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
---
|
| 195 |
|
| 196 |
# Zero-shot classification (`classify-dataset.py`)
|
|
|
|
| 1 |
---
|
| 2 |
viewer: false
|
| 3 |
+
tags: [uv-script, classification, fine-tuning, few-shot, zero-shot, setfit, gliner2, vllm, structured-outputs, hf-jobs]
|
| 4 |
---
|
| 5 |
|
| 6 |
# Classification Scripts
|
|
|
|
| 9 |
|
| 10 |
| Script | What it does |
|
| 11 |
|--------|--------------|
|
| 12 |
+
| [`classify-gliner2.py`](#zero-shot-first-then-fine-tune-gliner2) | **Label a dataset** with GLiNER2: zero-shot from label names, or with a `train-gliner2.py` model |
|
| 13 |
+
| [`train-gliner2.py`](#zero-shot-first-then-fine-tune-gliner2) | **Fine-tune** [GLiNER2](https://github.com/fastino-ai/GLiNER2), a small model (74M–287M) that already classifies zero-shot, and report the zero-shot score next to the fine-tuned one |
|
| 14 |
| [`train-setfit.py`](#few-shot-with-setfit-train-setfitpy) | **Few-shot** train a classifier from 8-64 labels per class with [SetFit](https://github.com/huggingface/setfit) — runs on CPU or GPU |
|
| 15 |
+
| [`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 |
|
| 16 |
| [`classify-dataset.py`](#zero-shot-classification-classify-datasetpy) | **Zero-shot** classify a dataset with an instruction LLM (SmolLM3 + vLLM, structured outputs) |
|
| 17 |
| `classify-dataset-sglang.py` | Zero-shot variant on SGLang (reasoning-aware `<think>` models) |
|
| 18 |
|
|
|
|
| 20 |
|
| 21 |
| Labels you have | Use | Hardware |
|
| 22 |
|---|---|---|
|
| 23 |
+
| none | `classify-gliner2.py --labels ...` for a cheap first pass; `classify-dataset.py` when the task needs an LLM's reasoning | small GPU (CPU works at ~1.4 rows/s); GPU |
|
| 24 |
| ~8-64 per class | `train-setfit.py` | CPU supported; GPU for faster training |
|
| 25 |
+
| a few hundred to a few thousand | `train-gliner2.py`, which also shows you what zero-shot already gets | small GPU (`t4-small`) |
|
| 26 |
+
| a few thousand or more | `train-classifier.py` | GPU |
|
| 27 |
|
| 28 |
The rungs chain: bootstrap labels with `classify-dataset.py`, review them, then train a small
|
| 29 |
dedicated model on what you kept.
|
| 30 |
|
| 31 |
+
## Zero-shot first, then fine-tune (GLiNER2)
|
| 32 |
|
| 33 |
+
Label a dataset with your own list of labels, see how far zero-shot gets you, then fine-tune a
|
| 34 |
+
small model on your labels, in minutes and for a few cents on one GPU. The result is a model
|
| 35 |
+
that returns a label and a probability for every row, and is small enough to run on a CPU.
|
| 36 |
|
| 37 |
+
[GLiNER2](https://github.com/fastino-ai/GLiNER2) is a small encoder that reads the label names
|
| 38 |
+
as part of its input, so it classifies with no training at all, and fine-tuning teaches it what
|
| 39 |
+
your labels mean in your data. (For entity extraction with the original GLiNER library, see
|
| 40 |
+
[`uv-scripts/gliner`](https://huggingface.co/datasets/uv-scripts/gliner).) Two scripts:
|
| 41 |
|
| 42 |
+
- **`train-gliner2.py`** scores the base model zero-shot, fine-tunes it on your labels, and
|
| 43 |
+
scores it again on the same held-out rows. The model card reports both next to the
|
| 44 |
+
majority-class floor, so you can see what the labels bought you.
|
| 45 |
+
- **`classify-gliner2.py`** labels a whole dataset. Pass `--labels` for zero-shot, or `--model`
|
| 46 |
+
with a `train-gliner2.py` output; the tasks and labels are read from the model repo.
|
| 47 |
+
Labels are passed as separate words; quote a label with spaces:
|
| 48 |
+
`--labels World Sports Business "Science and technology"`. A fine-tuned model is passed
|
| 49 |
+
by repo id: `--model username/gliner2-blbooks-genre`.
|
| 50 |
|
| 51 |
+
### Quick start
|
| 52 |
+
|
| 53 |
+
```bash
|
| 54 |
+
# fine-tune: British Library book titles -> Fiction / Non-fiction
|
| 55 |
+
hf jobs uv run --flavor t4-small --timeout 1h --secrets HF_TOKEN \
|
| 56 |
+
https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-gliner2.py \
|
| 57 |
+
biglam/blbooksgenre username/gliner2-blbooks-genre \
|
| 58 |
+
--dataset-config title_genre_classifiction --text-column title
|
| 59 |
+
|
| 60 |
+
# label a dataset with that model
|
| 61 |
+
hf jobs uv run --flavor t4-small --timeout 1h --secrets HF_TOKEN \
|
| 62 |
+
https://huggingface.co/datasets/uv-scripts/classification/raw/main/classify-gliner2.py \
|
| 63 |
+
biglam/blbooksgenre username/blbooks-genre-predictions \
|
| 64 |
+
--dataset-config title_genre_classifiction --text-column title --model username/gliner2-blbooks-genre
|
| 65 |
+
|
| 66 |
+
# or skip training: zero-shot from label names
|
| 67 |
+
hf jobs uv run --flavor t4-small --timeout 1h --secrets HF_TOKEN \
|
| 68 |
+
https://huggingface.co/datasets/uv-scripts/classification/raw/main/classify-gliner2.py \
|
| 69 |
+
fancyzhx/ag_news username/ag-news-topics --split test \
|
| 70 |
+
--labels World Sports Business "Science and technology" --task-name topic
|
| 71 |
```
|
| 72 |
|
| 73 |
+
The second command labels the same rows the model was trained on, so it shows the workflow, not
|
| 74 |
+
the model's accuracy; the held-out scores are on the model card. For real use, point it at data
|
| 75 |
+
the model has not seen. Outputs are **private by default** (`--public` to opt out).
|
|
|
|
| 76 |
|
| 77 |
+
These commands use the default base model, `fastino/gliner2.5-multi-v1` (multilingual). For
|
| 78 |
+
English text, `--base-model fastino/gliner2.5-base-v1` is smaller and faster;
|
| 79 |
+
`gliner2.5-small-v1` is the fastest and loses about 4 points on the 52-tag example. See [Choosing a model size](#choosing-a-model-size).
|
| 80 |
|
| 81 |
+
### What it buys you
|
|
|
|
|
|
|
| 82 |
|
| 83 |
+
| Dataset | Task | Labels | Train rows × epochs | Train time | Train cost | Metric | Majority floor | Zero-shot | Fine-tuned |
|
| 84 |
+
|---|---|---|---|---|---|---|---|---|---|
|
| 85 |
+
| [`biglam/blbooksgenre`](https://huggingface.co/datasets/biglam/blbooksgenre) (book titles) | single-label | 2 | 1,562 × 5 | 141s | $0.02 | accuracy | 0.747 | 0.767 (0.753–0.782) | **0.907** (0.897–0.925) |
|
| 86 |
+
| [`fancyzhx/ag_news`](https://huggingface.co/datasets/fancyzhx/ag_news) | single-label | 4 | 2,000 × 2 | 125s | $0.01 | accuracy | 0.268 | 0.718 | **0.852** |
|
| 87 |
+
| [`google-research-datasets/go_emotions`](https://huggingface.co/datasets/google-research-datasets/go_emotions) | multi-label | 28 | 2,000 × 2 | 216s | $0.02 | micro F1 | — | 0.265 | **0.464** |
|
| 88 |
+
| [`SetFit/TREC-QC`](https://huggingface.co/datasets/SetFit/TREC-QC), two tasks in one model | single-label ×2 | 6 + 50 | 5,452 × 3 | 1,761s | $0.20 | accuracy | 0.276 / 0.246 | 0.542 / 0.468 | **0.954 / 0.876** |
|
| 89 |
+
| same, on `a10g-small`, default batch size, bf16 | single-label ×2 | 6 + 50 | 5,452 × 3 | 509s | $0.14 | accuracy | 0.276 / 0.246 | not run | **0.944 / 0.872** |
|
| 90 |
+
| [`stanfordnlp/imdb`](https://huggingface.co/datasets/stanfordnlp/imdb) (reviews; 15% truncated at 2,000 characters) | single-label | 2 | 1,000 × 1 | 122s | $0.01 | accuracy | 0.500 | 0.777 | **0.840** |
|
| 91 |
+
| Hub dataset task tags ([worked example](#worked-example-tagging-hub-datasets)), `--base-model fastino/gliner2.5-base-v1 --label-augmentation off`, on `rtx-pro-6000` | single-label choice from a fixed set | 52 | 16,000 × 5 | 17 min | ~$1.50 | top-1 in the owner's tags | 0.320 (always "text-generation") | 0.102 | **0.690** (2 seeds: 0.695 / 0.686) |
|
| 92 |
|
| 93 |
+
Most rows are single, deliberately small runs that test the script, not tuned results. Seed ranges,
|
| 94 |
+
out-of-memory history and GPU comparisons are in [GLINER2-NOTES.md](GLINER2-NOTES.md).
|
| 95 |
|
| 96 |
+
### Choosing a model size
|
| 97 |
|
| 98 |
+
| Base model | Params | Use it when | Hub-tags top-1 | CPU latency per row (free Space, 2 vCPU) | GPU (L4, fp16) |
|
| 99 |
+
| -------------------------------------- | ------ | ------------------------------------------ | -------------- | ---------------------------------------- | -------------- |
|
| 100 |
+
| `fastino/gliner2.5-small-v1` | 74M | speed matters most | 0.653 | ~0.3 s | ~19 ms |
|
| 101 |
+
| `fastino/gliner2.5-base-v1` | 194M | English text; the best accuracy per second | 0.690 | ~0.7–1 s | ~19 ms |
|
| 102 |
+
| `fastino/gliner2.5-multi-v1` (default) | 287M | non-English or mixed-language text | not measured | — | — |
|
| 103 |
+
|
| 104 |
+
On a GPU, base and small are equally fast per row; the difference only shows on a CPU.
|
| 105 |
+
|
| 106 |
+
For speed on a CPU, use plain fp32 PyTorch; see the notes for what did not work (int8, ONNX).
|
| 107 |
+
|
| 108 |
+
### Larger or fixed label sets
|
| 109 |
+
|
| 110 |
+
For tens of labels scored together (a taxonomy, a fixed tag list), or data in a bucket, see
|
| 111 |
+
[Larger or fixed label sets](GLINER2-NOTES.md#larger-or-fixed-label-sets) in the notes:
|
| 112 |
+
`--labels-file`, `--label-augmentation off`, local `--train-file`/`--eval-file` and `--export-predictions`.
|
| 113 |
+
|
| 114 |
+
### Worked example: tagging Hub datasets
|
| 115 |
+
|
| 116 |
+
A GLiNER2.5-base model fine-tuned with this script on 16,000 Hub datasets suggests task tags for
|
| 117 |
+
a dataset from its column names and first row, among the 52 tags the Hub offers. Its first
|
| 118 |
+
suggestion matches one of the owner's tags 69% of the time on 3,000 newer datasets from owners it
|
| 119 |
+
never saw. Owners' tags are a noisy target, so the true rate is higher.
|
| 120 |
+
[Model](https://huggingface.co/davanstrien/hub-task-tagger-gliner2.5-base) · [Demo](https://huggingface.co/spaces/davanstrien/hub-task-tagger) · [Notes on how it was trained](GLINER2-NOTES.md#a-larger-label-set-52-hub-task-tags)
|
| 121 |
+
|
| 122 |
+
### Good to know
|
| 123 |
+
|
| 124 |
+
- **Single-label and multi-label** are auto-detected from the label column; repeat `--label-column` to train several tasks in one model.
|
| 125 |
+
- **Label names are part of the prompt.** Real names (`Fiction`, `Sports`) work; integer codes make zero-shot meaningless.
|
| 126 |
+
- **Out of GPU memory, it restarts at a smaller batch size** and stops before pushing if even batch size 1 fails. Many labels or long texts want an `a10g-small`.
|
| 127 |
+
- **Always pass `--timeout`.** Older `hf` CLIs ignore the scripts' `[tool.hf-jobs]` header and stop the Job after 30 minutes.
|
| 128 |
+
|
| 129 |
+
More behaviour details, tested commands, findings and dead ends: [GLINER2-NOTES.md](GLINER2-NOTES.md).
|
| 130 |
|
| 131 |
## Few-shot with SetFit (`train-setfit.py`)
|
| 132 |
|
| 133 |
+
An alternative when you have only a handful of labelled examples per class (8-64) and want a sentence-transformer model.
|
| 134 |
+
|
| 135 |
Trains a [SetFit](https://github.com/huggingface/setfit) classifier from a handful of labelled
|
| 136 |
examples per class. SetFit finetunes a sentence-transformer body on contrastive pairs, then fits a
|
| 137 |
logistic regression head on the resulting embeddings.
|
|
|
|
| 247 |
> **Note**: a SetFit model is a sentence-transformer body plus a scikit-learn head. Load it with
|
| 248 |
> `SetFitModel.from_pretrained(repo)`, not `AutoModelForSequenceClassification`.
|
| 249 |
|
| 250 |
+
## Fine-tune a classifier (`train-classifier.py`)
|
| 251 |
+
|
| 252 |
+
Fine-tunes a text-classification encoder on any Hub dataset and pushes the trained model
|
| 253 |
+
back to the Hub — download, train, evaluate, push, and reload-verify in one job.
|
| 254 |
+
|
| 255 |
+
- **Default model**: [LiquidAI/LFM2.5-Encoder-350M](https://huggingface.co/LiquidAI/LFM2.5-Encoder-350M) — a bidirectional encoder that beats ModernBERT-base on GLUE/SuperGLUE and handles 8,192-token documents. Any Hub encoder works via `--model` (ModernBERT, BERT, DeBERTa, …).
|
| 256 |
+
- **Single-label and multi-label**, auto-detected from the label column (`ClassLabel`/string/int → cross-entropy; list of labels → BCE + per-label threshold tuning).
|
| 257 |
+
- **Round-trippable artifacts**: standard architectures produce standard models; encoders without a classification head (like LFM2.5) get a generic mean-pooling head pushed as custom code, so `AutoModelForSequenceClassification.from_pretrained(..., trust_remote_code=True)` always works.
|
| 258 |
+
|
| 259 |
+
```bash
|
| 260 |
+
# single-label (ag_news has a ClassLabel column)
|
| 261 |
+
hf jobs uv run --flavor a10g-small --secrets HF_TOKEN \
|
| 262 |
+
https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-classifier.py \
|
| 263 |
+
fancyzhx/ag_news username/news-classifier
|
| 264 |
+
|
| 265 |
+
# multi-label (go_emotions has a list-of-labels column)
|
| 266 |
+
hf jobs uv run --flavor a10g-small --secrets HF_TOKEN \
|
| 267 |
+
https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-classifier.py \
|
| 268 |
+
google-research-datasets/go_emotions username/emotion-classifier --label-column labels
|
| 269 |
+
```
|
| 270 |
+
|
| 271 |
+
Key options: `--model`, `--max-length` (512 default; up to 8192 with
|
| 272 |
+
`--gradient-checkpointing` and a small `--batch-size` on a10g/a100), `--epochs`, `--lr`,
|
| 273 |
+
`--batch-size`, `--max-samples` (smoke runs), `--eval-split` (auto-detects
|
| 274 |
+
validation/test, or holds out 10% of train). Run `uv run train-classifier.py --help` for all.
|
| 275 |
+
|
| 276 |
+
### Worked example: classify dataset cards by task
|
| 277 |
+
|
| 278 |
+
[`davanstrien/dataset-cards-with-task-categories`](https://huggingface.co/datasets/davanstrien/dataset-cards-with-task-categories)
|
| 279 |
+
contains 21k Hub dataset cards (frontmatter stripped) labelled with their `task_categories`
|
| 280 |
+
metadata — a real multi-label task over long documents:
|
| 281 |
+
|
| 282 |
+
```bash
|
| 283 |
+
hf jobs uv run --flavor a10g-small --secrets HF_TOKEN \
|
| 284 |
+
https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-classifier.py \
|
| 285 |
+
davanstrien/dataset-cards-with-task-categories username/dataset-card-task-classifier \
|
| 286 |
+
--label-column labels --max-length 1024 --batch-size 8 --grad-accum 2
|
| 287 |
+
```
|
| 288 |
+
|
| 289 |
+
The output model predicts likely task categories from a card's prose — e.g. for suggesting
|
| 290 |
+
metadata on datasets that lack it.
|
| 291 |
+
|
| 292 |
+
### Training a standard encoder instead
|
| 293 |
+
|
| 294 |
+
`--model answerdotai/ModernBERT-base` (or any encoder with a native classification head)
|
| 295 |
+
produces a plain, vLLM-servable model — pair it with
|
| 296 |
+
[`uv-scripts/vllm`](https://huggingface.co/datasets/uv-scripts/vllm)'s
|
| 297 |
+
`classify-dataset.py` for large-scale batch inference with the model you just trained.
|
| 298 |
+
|
| 299 |
---
|
| 300 |
|
| 301 |
# Zero-shot classification (`classify-dataset.py`)
|
classify-gliner2.py
ADDED
|
@@ -0,0 +1,461 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11,<3.14"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "gliner2[local]==2.0.0",
|
| 5 |
+
# "protobuf",
|
| 6 |
+
# "sentencepiece",
|
| 7 |
+
# "datasets>=4.0.0,<6",
|
| 8 |
+
# "huggingface-hub",
|
| 9 |
+
# ]
|
| 10 |
+
#
|
| 11 |
+
# [tool.hf-jobs]
|
| 12 |
+
# flavor = "t4-small"
|
| 13 |
+
# timeout = "1h"
|
| 14 |
+
# secrets = ["HF_TOKEN"]
|
| 15 |
+
# ///
|
| 16 |
+
"""
|
| 17 |
+
Classify a text column of a Hub dataset with GLiNER2 — zero-shot, or with your fine-tuned model.
|
| 18 |
+
|
| 19 |
+
GLiNER2 is a small encoder (74M to 287M parameters) that reads the label names as part of its
|
| 20 |
+
input. That gives two ways to use this script:
|
| 21 |
+
|
| 22 |
+
1. Zero-shot: pass the label names with --labels. No training and no LLM. A t4-small does about
|
| 23 |
+
33 rows/s; cpu-basic works but manages about 1.4 rows/s, so keep CPU for a few hundred rows.
|
| 24 |
+
2. Fine-tuned: pass --model with a repo produced by `train-gliner2.py`. The tasks and labels are
|
| 25 |
+
read from the model repo, so no --labels flag is needed.
|
| 26 |
+
|
| 27 |
+
Zero-shot on HF Jobs:
|
| 28 |
+
|
| 29 |
+
hf jobs uv run --flavor t4-small --timeout 1h --secrets HF_TOKEN \\
|
| 30 |
+
https://huggingface.co/datasets/uv-scripts/classification/raw/main/classify-gliner2.py \\
|
| 31 |
+
fancyzhx/ag_news username/ag-news-gliner2 \\
|
| 32 |
+
--labels World Sports Business "Science and technology" --max-samples 1000
|
| 33 |
+
|
| 34 |
+
With a fine-tuned model:
|
| 35 |
+
|
| 36 |
+
hf jobs uv run --flavor t4-small --timeout 1h --secrets HF_TOKEN \\
|
| 37 |
+
https://huggingface.co/datasets/uv-scripts/classification/raw/main/classify-gliner2.py \\
|
| 38 |
+
biglam/blbooksgenre username/blbooks-genre-predictions \\
|
| 39 |
+
--dataset-config title_genre_classifiction --text-column title \\
|
| 40 |
+
--model username/gliner2-blbooks-genre
|
| 41 |
+
|
| 42 |
+
Output: the original columns, plus `predicted_<task>` (a label, or a list of labels for a
|
| 43 |
+
multi-label task) and `predicted_<task>_confidence` for every task. The output dataset is
|
| 44 |
+
PRIVATE unless you pass --public.
|
| 45 |
+
|
| 46 |
+
Pass `--timeout` to `hf jobs uv run` for a big dataset: CLIs older than 1.32 ignore the
|
| 47 |
+
[tool.hf-jobs] header above and stop the job after 30 minutes, before anything is pushed.
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
import argparse
|
| 51 |
+
import json
|
| 52 |
+
import logging
|
| 53 |
+
import os
|
| 54 |
+
import shlex
|
| 55 |
+
import sys
|
| 56 |
+
import time
|
| 57 |
+
from collections import Counter
|
| 58 |
+
|
| 59 |
+
os.environ.setdefault("TQDM_DISABLE", "1")
|
| 60 |
+
|
| 61 |
+
import datasets
|
| 62 |
+
import torch
|
| 63 |
+
from datasets import Features, List, Value, load_dataset
|
| 64 |
+
from gliner2.classification import (
|
| 65 |
+
ClassificationConfig,
|
| 66 |
+
ClassificationSchema,
|
| 67 |
+
Classifier,
|
| 68 |
+
)
|
| 69 |
+
from huggingface_hub import DatasetCard, HfApi, hf_hub_download, login
|
| 70 |
+
from huggingface_hub.utils import (
|
| 71 |
+
EntryNotFoundError,
|
| 72 |
+
RepositoryNotFoundError,
|
| 73 |
+
disable_progress_bars,
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def configure_logging() -> logging.Logger:
|
| 78 |
+
"""Keep Jobs logs readable: root at WARNING, only this script's logger at INFO."""
|
| 79 |
+
logging.basicConfig(
|
| 80 |
+
level=logging.WARNING,
|
| 81 |
+
format="%(asctime)s | %(levelname)s | %(message)s",
|
| 82 |
+
datefmt="%H:%M:%S",
|
| 83 |
+
)
|
| 84 |
+
for noisy in ("httpx", "urllib3", "filelock", "huggingface_hub"):
|
| 85 |
+
logging.getLogger(noisy).setLevel(logging.WARNING)
|
| 86 |
+
disable_progress_bars()
|
| 87 |
+
if hasattr(datasets, "disable_progress_bars"):
|
| 88 |
+
datasets.disable_progress_bars()
|
| 89 |
+
|
| 90 |
+
script_logger = logging.getLogger("classify-gliner2")
|
| 91 |
+
script_logger.setLevel(logging.INFO)
|
| 92 |
+
return script_logger
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
logger = configure_logging()
|
| 96 |
+
|
| 97 |
+
SCRIPT_URL = (
|
| 98 |
+
"https://huggingface.co/datasets/uv-scripts/classification/raw/main/classify-gliner2.py"
|
| 99 |
+
)
|
| 100 |
+
DEFAULT_MODEL = "fastino/gliner2.5-multi-v1"
|
| 101 |
+
|
| 102 |
+
# Written into the model repo by train-gliner2.py: the tasks and labels the model was trained on.
|
| 103 |
+
SCHEMA_FILENAME = "classification_schema.json"
|
| 104 |
+
|
| 105 |
+
# GLiNER2 puts label names into the model prompt verbatim and rejects these strings.
|
| 106 |
+
FORBIDDEN_IN_LABELS = ("(", ")", "[P]", "[L]", "[C]", "[E]", "[R]", "[DESCRIPTION]", "[EXAMPLE]", "[OUTPUT]")
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def check_labels(labels: list) -> None:
|
| 110 |
+
for label in labels:
|
| 111 |
+
for token in FORBIDDEN_IN_LABELS:
|
| 112 |
+
if token in label:
|
| 113 |
+
sys.exit(
|
| 114 |
+
f"Label {label!r} contains {token!r}, which GLiNER2 does not allow in a label "
|
| 115 |
+
"name. Rephrase it, for example with a dash instead of brackets."
|
| 116 |
+
)
|
| 117 |
+
if len(set(labels)) != len(labels):
|
| 118 |
+
sys.exit(f"--labels contains a duplicate: {labels}")
|
| 119 |
+
if len(labels) < 2:
|
| 120 |
+
sys.exit("Pass at least two --labels.")
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def exit_model_not_found(model_id: str) -> None:
|
| 124 |
+
sys.exit(
|
| 125 |
+
f"Cannot read the model '{model_id}'. Check the repo ID. If the repo is private or gated, "
|
| 126 |
+
"make sure HF_TOKEN has access to it."
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def check_model_access(api: HfApi, model_id: str) -> None:
|
| 131 |
+
"""Stop with a clear message, before loading any data, if the model repo cannot be read."""
|
| 132 |
+
if os.path.isdir(model_id):
|
| 133 |
+
return
|
| 134 |
+
try:
|
| 135 |
+
api.model_info(model_id)
|
| 136 |
+
except RepositoryNotFoundError:
|
| 137 |
+
exit_model_not_found(model_id)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def load_trained_tasks(model_id: str):
|
| 141 |
+
"""Read the tasks that train-gliner2.py recorded in the model repo, or return None."""
|
| 142 |
+
local_file = os.path.join(model_id, SCHEMA_FILENAME)
|
| 143 |
+
if os.path.isfile(local_file):
|
| 144 |
+
path = local_file
|
| 145 |
+
elif os.path.isdir(model_id):
|
| 146 |
+
return None
|
| 147 |
+
else:
|
| 148 |
+
try:
|
| 149 |
+
path = hf_hub_download(model_id, SCHEMA_FILENAME)
|
| 150 |
+
except EntryNotFoundError:
|
| 151 |
+
return None
|
| 152 |
+
except RepositoryNotFoundError:
|
| 153 |
+
# Also raised for a gated repo the token has not been granted.
|
| 154 |
+
exit_model_not_found(model_id)
|
| 155 |
+
with open(path) as handle:
|
| 156 |
+
return json.load(handle)["tasks"]
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def resolve_tasks(args) -> list:
|
| 160 |
+
"""Decide which tasks to run: --labels wins, otherwise the model repo's recorded tasks."""
|
| 161 |
+
if args.labels:
|
| 162 |
+
check_labels(args.labels)
|
| 163 |
+
return [{"name": args.task_name, "labels": args.labels, "multi_label": args.multi_label}]
|
| 164 |
+
|
| 165 |
+
tasks = load_trained_tasks(args.model)
|
| 166 |
+
if tasks is None:
|
| 167 |
+
sys.exit(
|
| 168 |
+
f"No --labels given, and '{args.model}' has no {SCHEMA_FILENAME}. Pass the label "
|
| 169 |
+
"names with --labels, or use a model trained with train-gliner2.py."
|
| 170 |
+
)
|
| 171 |
+
logger.info("Using the %d task(s) recorded in %s.", len(tasks), args.model)
|
| 172 |
+
return tasks
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def build_schema(tasks: list) -> ClassificationSchema:
|
| 176 |
+
schema = ClassificationSchema()
|
| 177 |
+
for task in tasks:
|
| 178 |
+
if task["multi_label"]:
|
| 179 |
+
schema.multi(task["name"], task["labels"])
|
| 180 |
+
else:
|
| 181 |
+
schema.single(task["name"], task["labels"])
|
| 182 |
+
return schema
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def label_counts_table(tasks: list, counts_by_task: dict, total: int) -> str:
|
| 186 |
+
lines = ["| Task | Label | Rows | Share |", "|---|---|---|---|"]
|
| 187 |
+
for task in tasks:
|
| 188 |
+
for label, count in counts_by_task[task["name"]].most_common():
|
| 189 |
+
lines.append(f"| `{task['name']}` | {label} | {count} | {count / total:.1%} |")
|
| 190 |
+
return "\n".join(lines)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
# The smallest Jobs flavor for each GPU, keyed by a fragment of the GPU's name. "L40" comes
|
| 194 |
+
# before "L4" because the first match wins.
|
| 195 |
+
GPU_NAME_TO_FLAVOR = {"T4": "t4-small", "A10G": "a10g-small", "L40": "l40sx1", "L4": "l4x1", "A100": "a100-large"}
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def jobs_flavor() -> str:
|
| 199 |
+
"""Return the Jobs hardware flavor, or "" when it is not known.
|
| 200 |
+
|
| 201 |
+
The docs say ACCELERATOR holds the flavor ("a10g-small"). On the t4-small and a10g-small
|
| 202 |
+
jobs that tested this script it held a bare "gpu", which is not a valid --flavor. So use
|
| 203 |
+
ACCELERATOR when it looks like a flavor, and otherwise name the smallest flavor that has
|
| 204 |
+
this GPU. A larger flavor of the same GPU reproduces the same result.
|
| 205 |
+
"""
|
| 206 |
+
hardware = os.environ.get("ACCELERATOR") or ""
|
| 207 |
+
looks_like_flavor = "-" in hardware or any(character.isdigit() for character in hardware)
|
| 208 |
+
if looks_like_flavor:
|
| 209 |
+
return hardware
|
| 210 |
+
if not torch.cuda.is_available():
|
| 211 |
+
return ""
|
| 212 |
+
gpu_name = torch.cuda.get_device_name(0)
|
| 213 |
+
for fragment, flavor in GPU_NAME_TO_FLAVOR.items():
|
| 214 |
+
if fragment in gpu_name:
|
| 215 |
+
return flavor
|
| 216 |
+
return ""
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def build_reproduce_command(args) -> str:
|
| 220 |
+
flavor = jobs_flavor() or "t4-small"
|
| 221 |
+
parts = [
|
| 222 |
+
f"hf jobs uv run --flavor {flavor} --timeout 1h --secrets HF_TOKEN \\",
|
| 223 |
+
f" {SCRIPT_URL} \\",
|
| 224 |
+
f" {shlex.quote(args.input_dataset)} {shlex.quote(args.output_dataset)}",
|
| 225 |
+
]
|
| 226 |
+
flags = []
|
| 227 |
+
if args.model != DEFAULT_MODEL:
|
| 228 |
+
flags.append(f"--model {shlex.quote(args.model)}")
|
| 229 |
+
if args.labels:
|
| 230 |
+
quoted = " ".join(shlex.quote(label) for label in args.labels)
|
| 231 |
+
flags.append(f"--labels {quoted}")
|
| 232 |
+
if args.task_name != "label":
|
| 233 |
+
flags.append(f"--task-name {shlex.quote(args.task_name)}")
|
| 234 |
+
if args.multi_label:
|
| 235 |
+
flags.append("--multi-label")
|
| 236 |
+
if args.dataset_config:
|
| 237 |
+
flags.append(f"--dataset-config {shlex.quote(args.dataset_config)}")
|
| 238 |
+
if args.text_column != "text":
|
| 239 |
+
flags.append(f"--text-column {shlex.quote(args.text_column)}")
|
| 240 |
+
if args.split != "train":
|
| 241 |
+
flags.append(f"--split {shlex.quote(args.split)}")
|
| 242 |
+
if args.max_samples:
|
| 243 |
+
flags.append(f"--max-samples {args.max_samples}")
|
| 244 |
+
if args.max_text_chars != 2000:
|
| 245 |
+
flags.append(f"--max-text-chars {args.max_text_chars}")
|
| 246 |
+
if args.public:
|
| 247 |
+
flags.append("--public")
|
| 248 |
+
if flags:
|
| 249 |
+
parts[-1] += " \\"
|
| 250 |
+
parts.append(" " + " ".join(flags))
|
| 251 |
+
return "\n".join(parts)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def build_card(args, tasks, counts_by_task, total, seconds, zero_shot: bool) -> str:
|
| 255 |
+
"""Dataset card with the canonical uv-scripts provenance stamp."""
|
| 256 |
+
on_jobs = os.environ.get("JOB_ID") is not None
|
| 257 |
+
hardware = jobs_flavor()
|
| 258 |
+
if on_jobs:
|
| 259 |
+
origin = "Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"
|
| 260 |
+
if hardware:
|
| 261 |
+
origin += f" (`{hardware}`)"
|
| 262 |
+
else:
|
| 263 |
+
origin = "Generated"
|
| 264 |
+
|
| 265 |
+
tags = ["uv-script", "gliner2", "text-classification"]
|
| 266 |
+
if on_jobs:
|
| 267 |
+
tags.append("hf-jobs")
|
| 268 |
+
tag_lines = "\n".join(f"- {tag}" for tag in tags)
|
| 269 |
+
|
| 270 |
+
if zero_shot:
|
| 271 |
+
how = (
|
| 272 |
+
"The model was used **zero-shot**: it was given only the label names and has never "
|
| 273 |
+
"seen labelled examples of this task. Treat the labels as a first pass to review, "
|
| 274 |
+
"not as ground truth."
|
| 275 |
+
)
|
| 276 |
+
else:
|
| 277 |
+
how = (
|
| 278 |
+
"The model was fine-tuned for these tasks. Its model card reports the held-out "
|
| 279 |
+
"scores. They apply only where this data resembles the training data."
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
column_lines = []
|
| 283 |
+
for task in tasks:
|
| 284 |
+
kind = "list of labels" if task["multi_label"] else "one label"
|
| 285 |
+
column_lines.append(f"- `predicted_{task['name']}`: {kind} from {task['labels']}")
|
| 286 |
+
note = " (empty when no label was selected)" if task["multi_label"] else ""
|
| 287 |
+
column_lines.append(f"- `predicted_{task['name']}_confidence`: model confidence in [0, 1]{note}")
|
| 288 |
+
column_block = "\n".join(column_lines)
|
| 289 |
+
|
| 290 |
+
return f"""---
|
| 291 |
+
tags:
|
| 292 |
+
{tag_lines}
|
| 293 |
+
---
|
| 294 |
+
|
| 295 |
+
# {args.output_dataset.split("/")[-1]}
|
| 296 |
+
|
| 297 |
+
[`{args.input_dataset}`](https://huggingface.co/datasets/{args.input_dataset}) (split `{args.split}`,
|
| 298 |
+
{total} rows) with the `{args.text_column}` column classified by
|
| 299 |
+
[`{args.model}`](https://huggingface.co/{args.model}), a [GLiNER2](https://github.com/fastino-ai/GLiNER2) model.
|
| 300 |
+
|
| 301 |
+
{how}
|
| 302 |
+
|
| 303 |
+
## Added columns
|
| 304 |
+
|
| 305 |
+
{column_block}
|
| 306 |
+
|
| 307 |
+
Texts were truncated to {args.max_text_chars} characters before classification.
|
| 308 |
+
The confidence is not calibrated. Check it against a labelled sample before you use it as a filter.
|
| 309 |
+
|
| 310 |
+
## Label distribution
|
| 311 |
+
|
| 312 |
+
{label_counts_table(tasks, counts_by_task, total)}
|
| 313 |
+
|
| 314 |
+
Classified {total} rows in {round(seconds)} seconds ({total / max(seconds, 1e-9):.0f} rows/s).
|
| 315 |
+
|
| 316 |
+
## Reproduction
|
| 317 |
+
|
| 318 |
+
{origin} with the [`classify-gliner2.py`]({SCRIPT_URL}) recipe from [uv-scripts](https://huggingface.co/uv-scripts). Run it yourself:
|
| 319 |
+
|
| 320 |
+
```bash
|
| 321 |
+
{build_reproduce_command(args)}
|
| 322 |
+
```
|
| 323 |
+
"""
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def main(args) -> None:
|
| 327 |
+
token = args.hf_token or os.environ.get("HF_TOKEN")
|
| 328 |
+
if not token:
|
| 329 |
+
sys.exit("No HF token. Pass --hf-token or run with --secrets HF_TOKEN.")
|
| 330 |
+
login(token=token)
|
| 331 |
+
|
| 332 |
+
# push_to_hub(private=True) leaves an existing repo's visibility alone, so check before the work.
|
| 333 |
+
api = HfApi(token=token)
|
| 334 |
+
output_exists = api.repo_exists(args.output_dataset, repo_type="dataset")
|
| 335 |
+
if not args.public and output_exists and not api.repo_info(args.output_dataset, repo_type="dataset").private:
|
| 336 |
+
sys.exit(
|
| 337 |
+
f"{args.output_dataset} already exists and is public. Pass --public to push there "
|
| 338 |
+
"anyway, or choose a new dataset name."
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
check_model_access(api, args.model)
|
| 342 |
+
tasks = resolve_tasks(args)
|
| 343 |
+
for task in tasks:
|
| 344 |
+
logger.info("Task '%s': %s", task["name"], task["labels"])
|
| 345 |
+
|
| 346 |
+
logger.info("Loading %s (split %s)", args.input_dataset, args.split)
|
| 347 |
+
dataset = load_dataset(args.input_dataset, args.dataset_config, split=args.split)
|
| 348 |
+
if args.text_column not in dataset.column_names:
|
| 349 |
+
sys.exit(f"Text column '{args.text_column}' not found. Columns are: {dataset.column_names}.")
|
| 350 |
+
for task in tasks:
|
| 351 |
+
for column in (f"predicted_{task['name']}", f"predicted_{task['name']}_confidence"):
|
| 352 |
+
if column in dataset.column_names:
|
| 353 |
+
sys.exit(f"The dataset already has a '{column}' column. Pass a different --task-name.")
|
| 354 |
+
if args.max_samples and len(dataset) > args.max_samples:
|
| 355 |
+
dataset = dataset.select(range(args.max_samples))
|
| 356 |
+
logger.info("Rows to classify: %d", len(dataset))
|
| 357 |
+
|
| 358 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 359 |
+
if device == "cpu":
|
| 360 |
+
logger.warning("No GPU found; classifying on CPU. Expect about 1-2 rows per second on cpu-basic.")
|
| 361 |
+
# from_pretrained(device=...) does not move the weights in gliner2 2.0.0; .to() does.
|
| 362 |
+
classifier = Classifier.from_pretrained(args.model).to(device=device).eval()
|
| 363 |
+
schema = build_schema(tasks)
|
| 364 |
+
config = ClassificationConfig(batch_size=args.batch_size)
|
| 365 |
+
|
| 366 |
+
counts_by_task = {task["name"]: Counter() for task in tasks}
|
| 367 |
+
empty_texts = 0
|
| 368 |
+
|
| 369 |
+
def classify_batch(batch: dict) -> dict:
|
| 370 |
+
nonlocal empty_texts
|
| 371 |
+
texts = []
|
| 372 |
+
for value in batch[args.text_column]:
|
| 373 |
+
text = "" if value is None else str(value)
|
| 374 |
+
if not text.strip():
|
| 375 |
+
empty_texts += 1
|
| 376 |
+
# The model needs some input; a missing text gets a prediction we then blank out.
|
| 377 |
+
text = "-"
|
| 378 |
+
texts.append(text[: args.max_text_chars])
|
| 379 |
+
|
| 380 |
+
results = classifier.batch_classify(texts, schema, config=config)
|
| 381 |
+
|
| 382 |
+
new_columns = {}
|
| 383 |
+
for task in tasks:
|
| 384 |
+
name = task["name"]
|
| 385 |
+
predictions = []
|
| 386 |
+
confidences = []
|
| 387 |
+
for value, result in zip(batch[args.text_column], results):
|
| 388 |
+
if value is None or not str(value).strip():
|
| 389 |
+
predictions.append([] if task["multi_label"] else None)
|
| 390 |
+
confidences.append(None)
|
| 391 |
+
continue
|
| 392 |
+
if task["multi_label"]:
|
| 393 |
+
labels = list(result.selected(name))
|
| 394 |
+
predictions.append(labels)
|
| 395 |
+
counts_by_task[name].update(labels or ["(none selected)"])
|
| 396 |
+
else:
|
| 397 |
+
label = result.value(name)
|
| 398 |
+
predictions.append(label)
|
| 399 |
+
counts_by_task[name][label] += 1
|
| 400 |
+
confidence = result.confidence(name)
|
| 401 |
+
confidences.append(None if confidence is None else float(confidence))
|
| 402 |
+
new_columns[f"predicted_{name}"] = predictions
|
| 403 |
+
new_columns[f"predicted_{name}_confidence"] = confidences
|
| 404 |
+
return new_columns
|
| 405 |
+
|
| 406 |
+
# Declare the output types. Otherwise the first map batch sets them, and a batch where
|
| 407 |
+
# every confidence is None (no label selected, or no text) types the column as null and
|
| 408 |
+
# the next batch fails to write.
|
| 409 |
+
output_features = Features(dataset.features)
|
| 410 |
+
for task in tasks:
|
| 411 |
+
name = task["name"]
|
| 412 |
+
output_features[f"predicted_{name}"] = List(Value("string")) if task["multi_label"] else Value("string")
|
| 413 |
+
output_features[f"predicted_{name}_confidence"] = Value("float64")
|
| 414 |
+
|
| 415 |
+
started = time.time()
|
| 416 |
+
# One map batch holds several model batches, so progress is logged at a useful rate.
|
| 417 |
+
dataset = dataset.map(
|
| 418 |
+
classify_batch,
|
| 419 |
+
batched=True,
|
| 420 |
+
batch_size=args.batch_size * 8,
|
| 421 |
+
features=output_features,
|
| 422 |
+
load_from_cache_file=False,
|
| 423 |
+
)
|
| 424 |
+
seconds = time.time() - started
|
| 425 |
+
logger.info("Classified %d rows in %.0f seconds.", len(dataset), seconds)
|
| 426 |
+
if empty_texts:
|
| 427 |
+
logger.warning("%d rows had no text and were left unlabelled.", empty_texts)
|
| 428 |
+
for task in tasks:
|
| 429 |
+
logger.info("Task '%s' distribution: %s", task["name"], dict(counts_by_task[task["name"]].most_common(10)))
|
| 430 |
+
|
| 431 |
+
dataset.push_to_hub(args.output_dataset, private=not args.public)
|
| 432 |
+
card = build_card(args, tasks, counts_by_task, len(dataset), seconds, zero_shot=bool(args.labels))
|
| 433 |
+
DatasetCard(card).push_to_hub(args.output_dataset, repo_type="dataset")
|
| 434 |
+
logger.info("Pushed to https://huggingface.co/datasets/%s", args.output_dataset)
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
def parse_args():
|
| 438 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 439 |
+
parser.add_argument("input_dataset", help="Input dataset ID")
|
| 440 |
+
parser.add_argument("output_dataset", help="Output dataset ID (username/dataset-name)")
|
| 441 |
+
parser.add_argument("--model", default=DEFAULT_MODEL, help=f"GLiNER2 model: a base checkpoint for zero-shot, or a train-gliner2.py output (default: {DEFAULT_MODEL})")
|
| 442 |
+
parser.add_argument("--labels", nargs="+", help="Label names for zero-shot classification. Overrides the tasks recorded in the model repo.")
|
| 443 |
+
parser.add_argument("--task-name", default="label", help="Name of the --labels task; sets the output column names (default: label)")
|
| 444 |
+
parser.add_argument("--multi-label", action="store_true", help="With --labels: allow several labels, or none, per text")
|
| 445 |
+
parser.add_argument("--dataset-config", help="Dataset config name")
|
| 446 |
+
parser.add_argument("--text-column", default="text", help="Text column (default: text)")
|
| 447 |
+
parser.add_argument("--split", default="train", help="Split to classify (default: train)")
|
| 448 |
+
parser.add_argument("--max-samples", type=int, help="Classify only the first N rows")
|
| 449 |
+
parser.add_argument("--max-text-chars", type=int, default=2000, help="Truncate texts to this many characters (default: 2000)")
|
| 450 |
+
parser.add_argument("--batch-size", type=int, default=32, help="Model batch size (default: 32)")
|
| 451 |
+
parser.add_argument("--public", action="store_true", help="Make the output dataset public (default: private)")
|
| 452 |
+
parser.add_argument("--private", action="store_true", help="Accepted for older commands; private is now the default")
|
| 453 |
+
parser.add_argument("--hf-token", help="HF token (or set HF_TOKEN)")
|
| 454 |
+
args = parser.parse_args()
|
| 455 |
+
if args.public and args.private:
|
| 456 |
+
parser.error("Pass --public or --private, not both.")
|
| 457 |
+
return args
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
if __name__ == "__main__":
|
| 461 |
+
main(parse_args())
|
train-gliner2.py
ADDED
|
@@ -0,0 +1,1279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11,<3.14"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "gliner2[train]==2.0.0",
|
| 5 |
+
# "protobuf",
|
| 6 |
+
# "sentencepiece",
|
| 7 |
+
# "datasets>=4.0.0,<6",
|
| 8 |
+
# "scikit-learn",
|
| 9 |
+
# "huggingface-hub",
|
| 10 |
+
# ]
|
| 11 |
+
#
|
| 12 |
+
# [tool.hf-jobs]
|
| 13 |
+
# flavor = "t4-small"
|
| 14 |
+
# timeout = "1h"
|
| 15 |
+
# secrets = ["HF_TOKEN"]
|
| 16 |
+
# ///
|
| 17 |
+
"""
|
| 18 |
+
Fine-tune GLiNER2 into a text classifier — a small model (74M to 287M parameters, depending on
|
| 19 |
+
the base checkpoint) that already works zero-shot.
|
| 20 |
+
|
| 21 |
+
GLiNER2 reads the label names as part of its input, so it classifies with no training at all.
|
| 22 |
+
This script measures that zero-shot score first, fine-tunes on your labels, then measures
|
| 23 |
+
again on the same held-out rows. The model card reports both numbers, so you can see what the
|
| 24 |
+
labels bought you. One model can answer several questions at once: pass --label-column more
|
| 25 |
+
than once and each column becomes a task.
|
| 26 |
+
|
| 27 |
+
Run on HF Jobs (t4-small is enough for a few thousand short texts):
|
| 28 |
+
|
| 29 |
+
hf jobs uv run --flavor t4-small --timeout 1h --secrets HF_TOKEN \\
|
| 30 |
+
https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-gliner2.py \\
|
| 31 |
+
biglam/blbooksgenre username/gliner2-blbooks-genre \\
|
| 32 |
+
--dataset-config title_genre_classifiction --text-column title
|
| 33 |
+
|
| 34 |
+
The output model repo is PRIVATE unless you pass --public.
|
| 35 |
+
|
| 36 |
+
The [tool.hf-jobs] header above gives `hf` CLI 1.32+ the defaults (t4-small, a 1 hour timeout,
|
| 37 |
+
the HF_TOKEN secret), so there `hf jobs uv run <script> <args>` is enough. Flags always win:
|
| 38 |
+
pass `--flavor a10g-small` for more memory and bf16, or `--timeout 3h` for a big run. Older CLIs
|
| 39 |
+
ignore the header, and Jobs then stops after 30 minutes; the model is pushed at the end. Pass
|
| 40 |
+
`--timeout` explicitly whenever you are not sure which CLI will launch the job.
|
| 41 |
+
|
| 42 |
+
Local files instead of a Hub dataset (for example files in a bucket mounted at /bucket):
|
| 43 |
+
|
| 44 |
+
hf jobs uv run --flavor a10g-small --timeout 2h --secrets HF_TOKEN \\
|
| 45 |
+
-v hf://buckets/username/my-bucket:/bucket \\
|
| 46 |
+
https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-gliner2.py \\
|
| 47 |
+
--train-file /bucket/train.jsonl \\
|
| 48 |
+
--eval-file calibration=/bucket/calibration.jsonl \\
|
| 49 |
+
--eval-file development=/bucket/development.jsonl \\
|
| 50 |
+
--labels-file /bucket/labels.json --label-column labels \\
|
| 51 |
+
--no-push --output-dir /bucket/runs/gliner2 \\
|
| 52 |
+
--export-predictions /bucket/runs/gliner2/predictions
|
| 53 |
+
|
| 54 |
+
- --train-file / --eval-file NAME=PATH read JSON Lines files (repeat --eval-file for several
|
| 55 |
+
eval splits). Every eval file is scored in full, in file order, with no cap.
|
| 56 |
+
- --labels-file fixes the label set, and its order, for training, zero-shot and evaluation.
|
| 57 |
+
Every label in the data must be in it. Needs exactly one --label-column.
|
| 58 |
+
- --export-predictions DIR writes DIR/{base,finetuned}-{split}/predictions.jsonl, one line per
|
| 59 |
+
eval row: {"row": i, "probabilities": {task: {label: p}}, "logits": {task: {label: logit}}},
|
| 60 |
+
with every label present. "row" is the row's position in its eval file (or split).
|
| 61 |
+
- --no-push keeps the model in --output-dir/final and uploads nothing. A run manifest (all
|
| 62 |
+
arguments, the label-augmentation config and package versions) is written to --output-dir,
|
| 63 |
+
the export directory and the model folder.
|
| 64 |
+
- --label-augmentation off turns off gliner2's synthetic label names and label dropping during
|
| 65 |
+
training, so the model always sees the real, complete label set (see resolve_sampling_config).
|
| 66 |
+
|
| 67 |
+
Metrics match `train-classifier.py` and `train-setfit.py` (accuracy + macro F1 on a held-out
|
| 68 |
+
split), so the three are directly comparable at equal eval settings.
|
| 69 |
+
|
| 70 |
+
NOTE: the output is a GLiNER2 checkpoint. It loads with
|
| 71 |
+
`gliner2.classification.Classifier.from_pretrained(repo)`, NOT `AutoModelForSequenceClassification`.
|
| 72 |
+
Apply it to a whole dataset with the sibling `classify-gliner2.py`.
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
import argparse
|
| 76 |
+
import dataclasses
|
| 77 |
+
import importlib.metadata
|
| 78 |
+
import json
|
| 79 |
+
import logging
|
| 80 |
+
import os
|
| 81 |
+
import shlex
|
| 82 |
+
import sys
|
| 83 |
+
import time
|
| 84 |
+
from collections import Counter
|
| 85 |
+
|
| 86 |
+
# tqdm reads TQDM_DISABLE when it is imported, so this must be set before any third-party import
|
| 87 |
+
# pulls tqdm in. Jobs logs have no TTY, so progress bars arrive as hundreds of near-identical lines.
|
| 88 |
+
# (The gliner2 trainer passes disable=False to its own bar, so its training bar still prints.)
|
| 89 |
+
os.environ.setdefault("TQDM_DISABLE", "1")
|
| 90 |
+
|
| 91 |
+
import datasets
|
| 92 |
+
import torch
|
| 93 |
+
from datasets import ClassLabel, Dataset, load_dataset
|
| 94 |
+
from gliner2 import AutoExtractor
|
| 95 |
+
from gliner2.classification import (
|
| 96 |
+
ClassificationConfig,
|
| 97 |
+
ClassificationSchema,
|
| 98 |
+
Classifier,
|
| 99 |
+
)
|
| 100 |
+
from gliner2.processor import SamplingConfig
|
| 101 |
+
from gliner2.training.data import Classification, InputExample
|
| 102 |
+
from gliner2.training.trainer import ExtractorTrainer, TrainingConfig
|
| 103 |
+
from huggingface_hub import HfApi, login
|
| 104 |
+
from huggingface_hub.utils import disable_progress_bars
|
| 105 |
+
from sklearn.metrics import accuracy_score, f1_score
|
| 106 |
+
from sklearn.preprocessing import MultiLabelBinarizer
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def configure_logging() -> logging.Logger:
|
| 110 |
+
"""Keep Jobs logs readable: root at WARNING, only this script's logger at INFO."""
|
| 111 |
+
logging.basicConfig(
|
| 112 |
+
level=logging.WARNING,
|
| 113 |
+
format="%(asctime)s | %(levelname)s | %(message)s",
|
| 114 |
+
datefmt="%H:%M:%S",
|
| 115 |
+
)
|
| 116 |
+
for noisy in ("httpx", "urllib3", "filelock", "huggingface_hub"):
|
| 117 |
+
logging.getLogger(noisy).setLevel(logging.WARNING)
|
| 118 |
+
disable_progress_bars()
|
| 119 |
+
if hasattr(datasets, "disable_progress_bars"):
|
| 120 |
+
datasets.disable_progress_bars()
|
| 121 |
+
|
| 122 |
+
script_logger = logging.getLogger("train-gliner2")
|
| 123 |
+
script_logger.setLevel(logging.INFO)
|
| 124 |
+
return script_logger
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
logger = configure_logging()
|
| 128 |
+
|
| 129 |
+
SCRIPT_URL = (
|
| 130 |
+
"https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-gliner2.py"
|
| 131 |
+
)
|
| 132 |
+
DEFAULT_BASE_MODEL = "fastino/gliner2.5-multi-v1"
|
| 133 |
+
|
| 134 |
+
# The file this script adds to the model repo. It records the tasks and label names the model
|
| 135 |
+
# was trained on, so classify-gliner2.py can rebuild the same schema without any flags.
|
| 136 |
+
SCHEMA_FILENAME = "classification_schema.json"
|
| 137 |
+
|
| 138 |
+
# Written next to the model, in --output-dir and in the export directory: the arguments,
|
| 139 |
+
# label-augmentation config and package versions of the run.
|
| 140 |
+
MANIFEST_FILENAME = "run_manifest.json"
|
| 141 |
+
|
| 142 |
+
# A column added to every eval split before any row is dropped, so exported predictions can
|
| 143 |
+
# name each row's position in the original file or split.
|
| 144 |
+
ROW_COLUMN = "__row__"
|
| 145 |
+
|
| 146 |
+
# After this many out-of-memory training steps, stop and retry smaller. See StopOnRepeatedOOM.
|
| 147 |
+
MAX_OOM_STEPS = 5
|
| 148 |
+
|
| 149 |
+
# GLiNER2 puts label names into the model prompt verbatim. Its inference schema rejects these
|
| 150 |
+
# strings, but its trainer accepts them — so a label like "manuscripts (documents)" trains
|
| 151 |
+
# without complaint and then cannot be predicted. We clean labels once, before either side.
|
| 152 |
+
RESERVED_MARKERS = ("[P]", "[L]", "[C]", "[E]", "[R]", "[DESCRIPTION]", "[EXAMPLE]", "[OUTPUT]")
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def clean_label(label: str) -> str:
|
| 156 |
+
"""Make one label name safe for the GLiNER2 prompt."""
|
| 157 |
+
cleaned = label.replace("(", " ").replace(")", " ")
|
| 158 |
+
cleaned = " ".join(cleaned.split())
|
| 159 |
+
if not cleaned:
|
| 160 |
+
sys.exit(f"Label {label!r} is empty after cleaning. Rename it in the dataset.")
|
| 161 |
+
for marker in RESERVED_MARKERS:
|
| 162 |
+
if marker in cleaned:
|
| 163 |
+
sys.exit(
|
| 164 |
+
f"Label {label!r} contains {marker!r}, which GLiNER2 reserves for its prompt. "
|
| 165 |
+
"Rename it in the dataset."
|
| 166 |
+
)
|
| 167 |
+
return cleaned
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def is_multi_label_column(dataset: Dataset, column: str) -> bool:
|
| 171 |
+
"""A list-valued column is a multi-label task."""
|
| 172 |
+
feature = dataset.features.get(column)
|
| 173 |
+
# A Sequence/list feature carries an inner `feature`.
|
| 174 |
+
return getattr(feature, "feature", None) is not None
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def label_feature(dataset: Dataset, column: str):
|
| 178 |
+
"""Return the ClassLabel that types this column, or None if the labels are plain values."""
|
| 179 |
+
feature = dataset.features.get(column)
|
| 180 |
+
inner = getattr(feature, "feature", None)
|
| 181 |
+
if isinstance(feature, ClassLabel):
|
| 182 |
+
return feature
|
| 183 |
+
if isinstance(inner, ClassLabel):
|
| 184 |
+
return inner
|
| 185 |
+
return None
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def decode_label(value, class_label) -> str:
|
| 189 |
+
"""Turn one raw label value into its cleaned name."""
|
| 190 |
+
if class_label is not None:
|
| 191 |
+
return clean_label(class_label.int2str(int(value)))
|
| 192 |
+
return clean_label(str(value))
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def decode_column(dataset: Dataset, column: str) -> list:
|
| 196 |
+
"""Return the gold labels for a column: a name per row, or a sorted list of names per row.
|
| 197 |
+
|
| 198 |
+
Decoding uses this split's OWN feature. A named --eval-split can order its ClassLabel
|
| 199 |
+
differently from the train split, and decoding through the train names would silently
|
| 200 |
+
score against the wrong table.
|
| 201 |
+
"""
|
| 202 |
+
class_label = label_feature(dataset, column)
|
| 203 |
+
multi = is_multi_label_column(dataset, column)
|
| 204 |
+
decoded = []
|
| 205 |
+
for value in dataset[column]:
|
| 206 |
+
if multi:
|
| 207 |
+
names = {decode_label(item, class_label) for item in (value or [])}
|
| 208 |
+
decoded.append(sorted(names))
|
| 209 |
+
else:
|
| 210 |
+
decoded.append(decode_label(value, class_label))
|
| 211 |
+
return decoded
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def drop_unlabelled_rows(dataset: Dataset, columns: list, text_column: str, split_name: str) -> Dataset:
|
| 215 |
+
"""Remove rows with no text, or with a missing or blank single-label value.
|
| 216 |
+
|
| 217 |
+
An empty LIST in a multi-label column is kept: "none of these labels" is a valid answer,
|
| 218 |
+
and the model needs to see it to learn when to select nothing.
|
| 219 |
+
"""
|
| 220 |
+
# In a ClassLabel column, -1 is the Hub convention for "no label" (common in test splits).
|
| 221 |
+
typed_columns = [column for column in columns if isinstance(dataset.features.get(column), ClassLabel)]
|
| 222 |
+
|
| 223 |
+
def is_usable(example) -> bool:
|
| 224 |
+
text = example[text_column]
|
| 225 |
+
if text is None or not str(text).strip():
|
| 226 |
+
return False
|
| 227 |
+
for column in columns:
|
| 228 |
+
value = example[column]
|
| 229 |
+
if isinstance(value, list):
|
| 230 |
+
continue
|
| 231 |
+
if value is None:
|
| 232 |
+
return False
|
| 233 |
+
if isinstance(value, str) and not value.strip():
|
| 234 |
+
return False
|
| 235 |
+
if column in typed_columns and value < 0:
|
| 236 |
+
return False
|
| 237 |
+
return True
|
| 238 |
+
|
| 239 |
+
kept = dataset.filter(is_usable)
|
| 240 |
+
dropped = len(dataset) - len(kept)
|
| 241 |
+
if dropped:
|
| 242 |
+
logger.warning(
|
| 243 |
+
"Dropped %d %s rows with no text or a missing label (%d remain).",
|
| 244 |
+
dropped, split_name, len(kept),
|
| 245 |
+
)
|
| 246 |
+
if len(kept) == 0:
|
| 247 |
+
sys.exit(
|
| 248 |
+
f"No '{split_name}' rows are left after dropping rows with no text or a missing label "
|
| 249 |
+
f"({len(dataset)} before). Check --text-column and --label-column, or pick another split."
|
| 250 |
+
)
|
| 251 |
+
return kept
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def pick_eval_split(dataset_id, config, train_split, requested):
|
| 255 |
+
"""Resolve which split to evaluate on, matching train-classifier.py's precedence."""
|
| 256 |
+
if requested:
|
| 257 |
+
if requested == train_split:
|
| 258 |
+
sys.exit(
|
| 259 |
+
f"--eval-split and --train-split are both '{requested}'. Evaluating on the "
|
| 260 |
+
"training data would report a meaningless score."
|
| 261 |
+
)
|
| 262 |
+
return requested
|
| 263 |
+
|
| 264 |
+
available = datasets.get_dataset_split_names(dataset_id, config)
|
| 265 |
+
for candidate in ("validation", "test"):
|
| 266 |
+
if candidate in available and candidate != train_split:
|
| 267 |
+
logger.info("Using the '%s' split for evaluation.", candidate)
|
| 268 |
+
return candidate
|
| 269 |
+
return None
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def split_train_eval(args, eval_split, first_label_column):
|
| 273 |
+
"""Load the train split, and either the named eval split or a carve-out of train."""
|
| 274 |
+
train_data = load_dataset(args.input_dataset, args.dataset_config, split=args.train_split)
|
| 275 |
+
|
| 276 |
+
if eval_split:
|
| 277 |
+
eval_data = load_dataset(args.input_dataset, args.dataset_config, split=eval_split)
|
| 278 |
+
return train_data, eval_data
|
| 279 |
+
|
| 280 |
+
logger.info("No eval split found; carving %.0f%% off the train split.", args.eval_fraction * 100)
|
| 281 |
+
# Stratify when the first label column is typed, so a rare class cannot vanish from a small carve.
|
| 282 |
+
feature = train_data.features.get(first_label_column)
|
| 283 |
+
stratify = first_label_column if isinstance(feature, ClassLabel) else None
|
| 284 |
+
try:
|
| 285 |
+
parts = train_data.train_test_split(
|
| 286 |
+
test_size=args.eval_fraction, seed=args.seed, stratify_by_column=stratify
|
| 287 |
+
)
|
| 288 |
+
except ValueError as error:
|
| 289 |
+
# Stratification needs at least two members of every class, so it fails on exactly the
|
| 290 |
+
# singleton classes it is meant to protect. An unstratified split is worse but usable.
|
| 291 |
+
logger.warning("Could not stratify the carve-out (%s). Using an unstratified split.", error)
|
| 292 |
+
parts = train_data.train_test_split(test_size=args.eval_fraction, seed=args.seed)
|
| 293 |
+
return parts["train"], parts["test"]
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def load_json_file(path: str) -> Dataset:
|
| 297 |
+
"""Load one JSON Lines file (a local path, or a path in a mounted bucket) as a Dataset."""
|
| 298 |
+
if not os.path.exists(path):
|
| 299 |
+
sys.exit(f"File not found: {path}")
|
| 300 |
+
return load_dataset("json", data_files=path, split="train")
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def load_splits(args):
|
| 304 |
+
"""Return the train split, the eval splits as {name: Dataset}, and whether eval was carved out.
|
| 305 |
+
|
| 306 |
+
With --train-file, every split comes from a local file and each --eval-file is its own
|
| 307 |
+
eval split. Otherwise one eval split comes from the Hub dataset, as before.
|
| 308 |
+
"""
|
| 309 |
+
if args.train_file:
|
| 310 |
+
logger.info("Loading the train file %s", args.train_file)
|
| 311 |
+
train_data = load_json_file(args.train_file)
|
| 312 |
+
eval_sets = {}
|
| 313 |
+
for name, path in args.eval_files.items():
|
| 314 |
+
logger.info("Loading eval split '%s' from %s", name, path)
|
| 315 |
+
eval_sets[name] = load_json_file(path)
|
| 316 |
+
return train_data, eval_sets, False
|
| 317 |
+
|
| 318 |
+
logger.info("Loading %s", args.input_dataset)
|
| 319 |
+
eval_split = pick_eval_split(args.input_dataset, args.dataset_config, args.train_split, args.eval_split)
|
| 320 |
+
train_data, eval_data = split_train_eval(args, eval_split, args.label_column[0])
|
| 321 |
+
carved_out = eval_split is None
|
| 322 |
+
return train_data, {eval_split or "eval": eval_data}, carved_out
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def add_row_numbers(dataset: Dataset) -> Dataset:
|
| 326 |
+
"""Record each row's position, so it survives dropped rows and is exported with predictions."""
|
| 327 |
+
if ROW_COLUMN in dataset.column_names:
|
| 328 |
+
sys.exit(f"The data already has a column named '{ROW_COLUMN}'. Rename it.")
|
| 329 |
+
return dataset.add_column(ROW_COLUMN, list(range(len(dataset))))
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def load_labels_file(path: str) -> list:
|
| 333 |
+
"""Read the fixed label set: a JSON list, or one label per line."""
|
| 334 |
+
if not os.path.exists(path):
|
| 335 |
+
sys.exit(f"Labels file not found: {path}")
|
| 336 |
+
with open(path) as handle:
|
| 337 |
+
content = handle.read()
|
| 338 |
+
if content.lstrip().startswith("["):
|
| 339 |
+
labels = json.loads(content)
|
| 340 |
+
else:
|
| 341 |
+
labels = [line.strip() for line in content.splitlines() if line.strip()]
|
| 342 |
+
if not labels:
|
| 343 |
+
sys.exit(f"Labels file {path} has no labels.")
|
| 344 |
+
return [str(label) for label in labels]
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def check_labels_in_set(tasks: list, gold_by_split: dict) -> None:
|
| 348 |
+
"""With --labels-file, every gold label in every split must be one of the fixed labels."""
|
| 349 |
+
for task in tasks:
|
| 350 |
+
allowed = set(task["labels"])
|
| 351 |
+
for split_name, gold_by_task in gold_by_split.items():
|
| 352 |
+
unknown = Counter()
|
| 353 |
+
for value in gold_by_task[task["name"]]:
|
| 354 |
+
row_labels = value if task["multi_label"] else [value]
|
| 355 |
+
for label in row_labels:
|
| 356 |
+
if label not in allowed:
|
| 357 |
+
unknown[label] += 1
|
| 358 |
+
if unknown:
|
| 359 |
+
sys.exit(
|
| 360 |
+
f"Task '{task['name']}', split '{split_name}': labels that are not in "
|
| 361 |
+
f"--labels-file: {dict(unknown.most_common(20))}"
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def prepare_texts(dataset: Dataset, text_column: str, max_text_chars: int, split_name: str) -> list:
|
| 366 |
+
"""Return the text for each row, truncated to max_text_chars."""
|
| 367 |
+
texts = []
|
| 368 |
+
truncated = 0
|
| 369 |
+
for value in dataset[text_column]:
|
| 370 |
+
text = str(value)
|
| 371 |
+
if len(text) > max_text_chars:
|
| 372 |
+
text = text[:max_text_chars]
|
| 373 |
+
truncated += 1
|
| 374 |
+
texts.append(text)
|
| 375 |
+
if truncated:
|
| 376 |
+
logger.warning(
|
| 377 |
+
"Truncated %d of %d %s texts to %d characters. Raise --max-text-chars if the label "
|
| 378 |
+
"depends on text past that point.",
|
| 379 |
+
truncated, len(texts), split_name, max_text_chars,
|
| 380 |
+
)
|
| 381 |
+
return texts
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def build_tasks(train_data: Dataset, label_columns: list, task_names: list, fixed_labels=None) -> list:
|
| 385 |
+
"""Describe one classification task per label column.
|
| 386 |
+
|
| 387 |
+
GLiNER2 reads the task name as part of its prompt, next to the label names, so --task-name
|
| 388 |
+
lets you call the task "genre" rather than "label". Do not expect much from it: on BL book
|
| 389 |
+
titles the zero-shot accuracy was 0.79 with "label" and 0.78 with "genre".
|
| 390 |
+
|
| 391 |
+
The label list comes from the TRAIN split. A label that appears only in the eval split
|
| 392 |
+
cannot be predicted, and evaluate() counts it as an error rather than hiding it.
|
| 393 |
+
With --labels-file (fixed_labels), the label list is that file, in its order, instead.
|
| 394 |
+
"""
|
| 395 |
+
tasks = []
|
| 396 |
+
for column, task_name in zip(label_columns, task_names):
|
| 397 |
+
multi = is_multi_label_column(train_data, column)
|
| 398 |
+
class_label = label_feature(train_data, column)
|
| 399 |
+
if fixed_labels is not None:
|
| 400 |
+
labels = [clean_label(name) for name in fixed_labels]
|
| 401 |
+
elif class_label is not None:
|
| 402 |
+
labels = [clean_label(name) for name in class_label.names]
|
| 403 |
+
else:
|
| 404 |
+
seen = set()
|
| 405 |
+
for value in decode_column(train_data, column):
|
| 406 |
+
if multi:
|
| 407 |
+
seen.update(value)
|
| 408 |
+
else:
|
| 409 |
+
seen.add(value)
|
| 410 |
+
labels = sorted(seen)
|
| 411 |
+
|
| 412 |
+
if fixed_labels is not None:
|
| 413 |
+
raw_names = list(fixed_labels)
|
| 414 |
+
elif class_label is not None:
|
| 415 |
+
raw_names = list(class_label.names)
|
| 416 |
+
else:
|
| 417 |
+
raw_names = []
|
| 418 |
+
for value in train_data[column]:
|
| 419 |
+
raw_names.extend((value or []) if multi else [value])
|
| 420 |
+
raw_names = sorted({str(name) for name in raw_names})
|
| 421 |
+
renamed = {name: clean_label(name) for name in raw_names if clean_label(name) != name}
|
| 422 |
+
if renamed:
|
| 423 |
+
logger.warning(
|
| 424 |
+
"Column '%s': GLiNER2 does not allow brackets in label names, so the model will "
|
| 425 |
+
"predict the cleaned names: %s", column, renamed,
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
# Check raw -> cleaned before trusting `labels`: for a plain string column the labels were
|
| 429 |
+
# cleaned on the way into a set, so two different raw labels could already have merged.
|
| 430 |
+
raw_by_cleaned = {}
|
| 431 |
+
for name in raw_names:
|
| 432 |
+
raw_by_cleaned.setdefault(clean_label(name), []).append(name)
|
| 433 |
+
merged = {cleaned: raws for cleaned, raws in raw_by_cleaned.items() if len(raws) > 1}
|
| 434 |
+
if merged:
|
| 435 |
+
sys.exit(
|
| 436 |
+
f"Column '{column}': different labels become identical after cleaning "
|
| 437 |
+
f"(brackets are removed): {merged}. Rename them in the dataset."
|
| 438 |
+
)
|
| 439 |
+
if len(set(labels)) != len(labels):
|
| 440 |
+
sys.exit(f"Column '{column}': two labels are identical after cleaning: {labels}")
|
| 441 |
+
if len(labels) < 2:
|
| 442 |
+
sys.exit(f"Column '{column}' has fewer than two labels: {labels}")
|
| 443 |
+
if all(label.lstrip("-").isdigit() for label in labels):
|
| 444 |
+
logger.warning(
|
| 445 |
+
"Column '%s' has numeric labels %s. GLiNER2 reads label NAMES, so the zero-shot "
|
| 446 |
+
"score will be meaningless and fine-tuning starts from nothing. A ClassLabel or "
|
| 447 |
+
"string column with real names will do better.",
|
| 448 |
+
column, labels[:6],
|
| 449 |
+
)
|
| 450 |
+
tasks.append({"name": clean_label(task_name), "column": column, "labels": labels, "multi_label": multi})
|
| 451 |
+
logger.info(
|
| 452 |
+
"Task '%s' (column '%s'): %d labels, %s.",
|
| 453 |
+
task_name, column, len(labels), "multi-label" if multi else "single-label",
|
| 454 |
+
)
|
| 455 |
+
return tasks
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
def build_training_examples(texts: list, gold_by_task: dict, tasks: list) -> list:
|
| 459 |
+
examples = []
|
| 460 |
+
for row, text in enumerate(texts):
|
| 461 |
+
classifications = []
|
| 462 |
+
for task in tasks:
|
| 463 |
+
classifications.append(
|
| 464 |
+
Classification(
|
| 465 |
+
task=task["name"],
|
| 466 |
+
labels=task["labels"],
|
| 467 |
+
true_label=gold_by_task[task["name"]][row],
|
| 468 |
+
# Only auto-inferred when a row has 2+ true labels, so state it.
|
| 469 |
+
multi_label=task["multi_label"],
|
| 470 |
+
)
|
| 471 |
+
)
|
| 472 |
+
examples.append(InputExample(text=text, classifications=classifications))
|
| 473 |
+
return examples
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
def build_schema(tasks: list) -> ClassificationSchema:
|
| 477 |
+
schema = ClassificationSchema()
|
| 478 |
+
for task in tasks:
|
| 479 |
+
if task["multi_label"]:
|
| 480 |
+
schema.multi(task["name"], task["labels"])
|
| 481 |
+
else:
|
| 482 |
+
schema.single(task["name"], task["labels"])
|
| 483 |
+
return schema
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
class TrainingOutOfMemory(Exception):
|
| 487 |
+
"""Raised when the GPU keeps running out of memory during training."""
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
class StopOnRepeatedOOM(logging.Handler):
|
| 491 |
+
"""Abort training when the gliner2 trainer keeps hitting CUDA out-of-memory.
|
| 492 |
+
|
| 493 |
+
The gliner2 trainer catches an OOM, skips that batch, logs a warning and carries on. On a
|
| 494 |
+
GPU that is too small for the batch, EVERY step is skipped: the job runs to the end, looks
|
| 495 |
+
healthy, and produces a model that never trained. (Seen on t4-small with 56 labels at batch
|
| 496 |
+
size 16: 1,006 of 1,020 steps skipped.) The trainer has no option to raise instead, so this
|
| 497 |
+
handler watches its log. An exception raised in emit() propagates out of the trainer's own
|
| 498 |
+
logger.warning() call, which stops trainer.train().
|
| 499 |
+
"""
|
| 500 |
+
|
| 501 |
+
def __init__(self, limit: int):
|
| 502 |
+
super().__init__(level=logging.WARNING)
|
| 503 |
+
self.limit = limit
|
| 504 |
+
self.oom_steps = 0
|
| 505 |
+
|
| 506 |
+
def emit(self, record: logging.LogRecord) -> None:
|
| 507 |
+
if "OOM at step" not in record.getMessage():
|
| 508 |
+
return
|
| 509 |
+
self.oom_steps += 1
|
| 510 |
+
if self.oom_steps >= self.limit:
|
| 511 |
+
raise TrainingOutOfMemory()
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def resolve_precision(requested: str) -> str:
|
| 515 |
+
"""Pick the training precision: bf16 where the GPU does it in hardware, else fp32.
|
| 516 |
+
|
| 517 |
+
gliner2 itself defaults the 2.5 models to bf16. torch.cuda.is_bf16_supported() also says yes
|
| 518 |
+
on a T4, where bf16 is emulated and slow, so this checks the compute capability instead
|
| 519 |
+
(8.0+ = Ampere and newer: A10G, L4, A100, ...). fp16 is not offered: it overflowed on T4.
|
| 520 |
+
"""
|
| 521 |
+
if requested != "auto":
|
| 522 |
+
return requested
|
| 523 |
+
if torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 8:
|
| 524 |
+
return "bf16"
|
| 525 |
+
return "fp32"
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def resolve_sampling_config(mode: str) -> SamplingConfig:
|
| 529 |
+
"""Pick the gliner2 training-time label augmentation.
|
| 530 |
+
|
| 531 |
+
"upstream" is gliner2 2.0.0's default SamplingConfig. For each classification task in each
|
| 532 |
+
training row, it replaces the real label names with "label 1", "label 2", ... half of the
|
| 533 |
+
time (synthetic_label_prob=0.5), and drops a random share of up to half of the labels
|
| 534 |
+
(remove_classification_label_prob=0.5; the true label is then put back only half of the
|
| 535 |
+
time). That teaches a general zero-shot model to cope with unseen label sets.
|
| 536 |
+
|
| 537 |
+
"off" is for a FIXED label set that is always scored in full: the model then always trains
|
| 538 |
+
on the real names and the complete label set, the same prompt it gets at inference.
|
| 539 |
+
Label-order shuffling stays on, and so does task-order shuffling: neither changes which
|
| 540 |
+
labels the model sees, and both stop it tying a label to a position in the prompt.
|
| 541 |
+
The other options only touch entities, relations and JSON structures, or label
|
| 542 |
+
descriptions and examples, which this script does not use.
|
| 543 |
+
"""
|
| 544 |
+
if mode == "upstream":
|
| 545 |
+
return SamplingConfig()
|
| 546 |
+
return SamplingConfig(synthetic_label_prob=0.0, remove_classification_label_prob=0.0)
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def package_versions() -> dict:
|
| 550 |
+
versions = {}
|
| 551 |
+
for package in ("gliner2", "torch", "transformers", "datasets", "huggingface-hub"):
|
| 552 |
+
try:
|
| 553 |
+
versions[package] = importlib.metadata.version(package)
|
| 554 |
+
except importlib.metadata.PackageNotFoundError:
|
| 555 |
+
versions[package] = None
|
| 556 |
+
return versions
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
def build_manifest(args, sampling_config: SamplingConfig, precision: str) -> dict:
|
| 560 |
+
"""Everything needed to tell two runs apart. The HF token is left out."""
|
| 561 |
+
settings = {key: value for key, value in vars(args).items() if key != "hf_token"}
|
| 562 |
+
return {
|
| 563 |
+
"script": SCRIPT_URL,
|
| 564 |
+
"args": settings,
|
| 565 |
+
"label_augmentation": args.label_augmentation,
|
| 566 |
+
"sampling_config": dataclasses.asdict(sampling_config),
|
| 567 |
+
"precision": precision,
|
| 568 |
+
"device": torch.cuda.get_device_name(0) if torch.cuda.is_available() else "cpu",
|
| 569 |
+
"job_id": os.environ.get("JOB_ID"),
|
| 570 |
+
"versions": package_versions(),
|
| 571 |
+
}
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
def write_manifest(manifest: dict, directories: list) -> None:
|
| 575 |
+
for directory in directories:
|
| 576 |
+
os.makedirs(directory, exist_ok=True)
|
| 577 |
+
path = os.path.join(directory, MANIFEST_FILENAME)
|
| 578 |
+
with open(path, "w") as handle:
|
| 579 |
+
json.dump(manifest, handle, indent=2)
|
| 580 |
+
logger.info("Wrote %s", path)
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def train_with_batch_fallback(args, examples: list, precision: str, sampling_config: SamplingConfig) -> int:
|
| 584 |
+
"""Train, and if the GPU runs out of memory, restart the script at a quarter of the batch size.
|
| 585 |
+
|
| 586 |
+
Gradient accumulation grows by the same factor, so the effective batch size (and the
|
| 587 |
+
number of optimizer steps) stays the same: the fallback costs time, not comparability.
|
| 588 |
+
|
| 589 |
+
The restart is a whole new process (os.execv). Retrying inside this process was tried and
|
| 590 |
+
does not work: after a failed run the gliner2 trainer's model and optimizer state stay on
|
| 591 |
+
the GPU (about 4.6 GB per attempt), so each retry starts with less memory than the last.
|
| 592 |
+
A new process gets a clean GPU. It parses the new --batch-size / --grad-accum itself, so
|
| 593 |
+
the model card's reproduce command describes the run that produced the model. The restart
|
| 594 |
+
also repeats the zero-shot scoring; that gives the same number and takes under a minute.
|
| 595 |
+
|
| 596 |
+
Returns the number of training steps that were skipped for lack of memory.
|
| 597 |
+
"""
|
| 598 |
+
model = AutoExtractor.from_pretrained(args.base_model)
|
| 599 |
+
# The trainer uses model.processor, and the processor reads sampling_config for every
|
| 600 |
+
# training row, so setting it here is what changes the training prompts.
|
| 601 |
+
model.processor.sampling_config = sampling_config
|
| 602 |
+
logger.info(
|
| 603 |
+
"Label augmentation '%s': %s",
|
| 604 |
+
args.label_augmentation, json.dumps(dataclasses.asdict(model.processor.sampling_config)),
|
| 605 |
+
)
|
| 606 |
+
config = TrainingConfig(
|
| 607 |
+
output_dir=args.output_dir,
|
| 608 |
+
num_epochs=args.epochs,
|
| 609 |
+
batch_size=args.batch_size,
|
| 610 |
+
gradient_accumulation_steps=args.grad_accum,
|
| 611 |
+
encoder_lr=args.encoder_lr,
|
| 612 |
+
task_lr=args.task_lr,
|
| 613 |
+
seed=args.seed,
|
| 614 |
+
# We score the held-out split ourselves, before and after, with the same code.
|
| 615 |
+
eval_strategy="no",
|
| 616 |
+
fp16=False,
|
| 617 |
+
bf16=(precision == "bf16"),
|
| 618 |
+
logging_steps=20,
|
| 619 |
+
)
|
| 620 |
+
oom_guard = StopOnRepeatedOOM(limit=MAX_OOM_STEPS)
|
| 621 |
+
logging.getLogger("gliner2.training.trainer").addHandler(oom_guard)
|
| 622 |
+
try:
|
| 623 |
+
result = ExtractorTrainer(model, config).train(train_data=examples)
|
| 624 |
+
# The trainer skips a batch that runs out of memory. On a short run every batch can be
|
| 625 |
+
# skipped without reaching MAX_OOM_STEPS, which would push an untrained model.
|
| 626 |
+
updates = result.get("total_steps") if isinstance(result, dict) else None
|
| 627 |
+
if updates != 0:
|
| 628 |
+
return oom_guard.oom_steps
|
| 629 |
+
if oom_guard.oom_steps == 0:
|
| 630 |
+
sys.exit("Stopped: training finished without a single optimizer update, so nothing was pushed.")
|
| 631 |
+
logger.warning("No optimizer update succeeded: every batch ran out of memory.")
|
| 632 |
+
except (TrainingOutOfMemory, torch.cuda.OutOfMemoryError):
|
| 633 |
+
# gliner2 catches out-of-memory in the forward and backward pass, but not in the
|
| 634 |
+
# optimizer step (for example while allocating optimizer state), so catch that here too.
|
| 635 |
+
pass
|
| 636 |
+
|
| 637 |
+
if args.batch_size == 1:
|
| 638 |
+
sys.exit(
|
| 639 |
+
"Stopped: the GPU ran out of memory even at batch size 1, so nothing was pushed. "
|
| 640 |
+
"Memory grows with number of labels x text length. Lower --max-text-chars, or use a "
|
| 641 |
+
"GPU with more memory (`--flavor a10g-small` has 24 GB, `--flavor a100-large` 80 GB)."
|
| 642 |
+
)
|
| 643 |
+
smaller = max(1, args.batch_size // 4)
|
| 644 |
+
grad_accum = args.grad_accum * (args.batch_size // smaller)
|
| 645 |
+
on_t4 = "T4" in torch.cuda.get_device_name(0)
|
| 646 |
+
logger.warning(
|
| 647 |
+
"The GPU ran out of memory at batch size %d. Restarting at batch size %d with %d gradient "
|
| 648 |
+
"accumulation steps (same effective batch).%s",
|
| 649 |
+
args.batch_size, smaller, grad_accum,
|
| 650 |
+
" `--flavor a10g-small` (24 GB) would be faster." if on_t4 else "",
|
| 651 |
+
)
|
| 652 |
+
sys.stdout.flush()
|
| 653 |
+
sys.stderr.flush()
|
| 654 |
+
# argparse keeps the LAST value of a repeated flag, so appending these overrides the originals.
|
| 655 |
+
os.execv(
|
| 656 |
+
sys.executable,
|
| 657 |
+
[sys.executable, *sys.argv, "--batch-size", str(smaller), "--grad-accum", str(grad_accum)],
|
| 658 |
+
)
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
def score_task(task: dict, gold: list, results: list) -> dict:
|
| 662 |
+
"""Accuracy-style metrics for one task, from decoded results."""
|
| 663 |
+
name = task["name"]
|
| 664 |
+
if task["multi_label"]:
|
| 665 |
+
predicted = [sorted(result.selected(name)) for result in results]
|
| 666 |
+
# Labels seen only in eval still count: the binarizer covers the union.
|
| 667 |
+
all_labels = sorted(set(task["labels"]) | {label for row in gold for label in row})
|
| 668 |
+
binarizer = MultiLabelBinarizer(classes=all_labels)
|
| 669 |
+
gold_matrix = binarizer.fit_transform(gold)
|
| 670 |
+
predicted_matrix = binarizer.transform(predicted)
|
| 671 |
+
return {
|
| 672 |
+
"f1_micro": round(f1_score(gold_matrix, predicted_matrix, average="micro", zero_division=0), 4),
|
| 673 |
+
"f1_macro": round(f1_score(gold_matrix, predicted_matrix, average="macro", zero_division=0), 4),
|
| 674 |
+
"exact_match": round(accuracy_score(gold_matrix, predicted_matrix), 4),
|
| 675 |
+
}
|
| 676 |
+
predicted = [result.value(name) for result in results]
|
| 677 |
+
# The majority-class rate is the floor any classifier must clear to be worth having.
|
| 678 |
+
majority = Counter(gold).most_common(1)[0][1] / len(gold)
|
| 679 |
+
return {
|
| 680 |
+
"accuracy": round(accuracy_score(gold, predicted), 4),
|
| 681 |
+
"f1_macro": round(f1_score(gold, predicted, average="macro", zero_division=0), 4),
|
| 682 |
+
"majority_baseline": round(majority, 4),
|
| 683 |
+
}
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
def write_predictions(path: str, rows: list, scores: list, results: list, tasks: list) -> None:
|
| 687 |
+
"""One JSON line per eval row, in order, with the probability and raw logit of EVERY label.
|
| 688 |
+
|
| 689 |
+
Logits are the model's per-label scores before any activation (ClassificationScores.tasks).
|
| 690 |
+
Probabilities are gliner2's own: softmax over the labels for a single-label task, a
|
| 691 |
+
sigmoid per label for a multi-label task.
|
| 692 |
+
"""
|
| 693 |
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
| 694 |
+
with open(path, "w") as handle:
|
| 695 |
+
for row, score, result in zip(rows, scores, results):
|
| 696 |
+
record = {"row": row, "probabilities": {}, "logits": {}}
|
| 697 |
+
for task in tasks:
|
| 698 |
+
name = task["name"]
|
| 699 |
+
probabilities = result.probabilities(name)
|
| 700 |
+
logits = score.tasks[name]
|
| 701 |
+
record["probabilities"][name] = {label: float(probabilities[label]) for label in task["labels"]}
|
| 702 |
+
record["logits"][name] = {label: float(logits[label]) for label in task["labels"]}
|
| 703 |
+
handle.write(json.dumps(record) + "\n")
|
| 704 |
+
logger.info("Wrote %d predictions to %s", len(rows), path)
|
| 705 |
+
|
| 706 |
+
|
| 707 |
+
def evaluate(model_path: str, eval_sets: dict, tasks: list, batch_size: int, export_dir=None, export_name="") -> dict:
|
| 708 |
+
"""Load a GLiNER2 checkpoint once, predict every task on every eval split, and score each task.
|
| 709 |
+
|
| 710 |
+
eval_sets maps a split name to {"texts", "gold", "rows"}. With export_dir, each split's
|
| 711 |
+
predictions are also written to export_dir/<export_name>-<split>/predictions.jsonl.
|
| 712 |
+
Returns {split name: metrics}.
|
| 713 |
+
"""
|
| 714 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 715 |
+
# from_pretrained(device=...) does not move the weights in gliner2 2.0.0; .to() does.
|
| 716 |
+
classifier = Classifier.from_pretrained(model_path).to(device=device).eval()
|
| 717 |
+
parameters = sum(parameter.numel() for parameter in classifier.model.parameters())
|
| 718 |
+
schema = build_schema(tasks)
|
| 719 |
+
config = ClassificationConfig(batch_size=batch_size)
|
| 720 |
+
|
| 721 |
+
metrics_by_split = {}
|
| 722 |
+
for split_name, eval_set in eval_sets.items():
|
| 723 |
+
started = time.time()
|
| 724 |
+
# batch_classify() is batch_score() + decode(); calling both here keeps the raw logits.
|
| 725 |
+
scores = classifier.batch_score(eval_set["texts"], schema, config=config)
|
| 726 |
+
results = [classifier.decode(score, schema, config=config) for score in scores]
|
| 727 |
+
elapsed = time.time() - started
|
| 728 |
+
|
| 729 |
+
metrics = {}
|
| 730 |
+
for task in tasks:
|
| 731 |
+
metrics[task["name"]] = score_task(task, eval_set["gold"][task["name"]], results)
|
| 732 |
+
metrics_by_split[split_name] = {
|
| 733 |
+
"tasks": metrics,
|
| 734 |
+
"eval_examples": len(eval_set["texts"]),
|
| 735 |
+
"predict_seconds": round(elapsed, 1),
|
| 736 |
+
"parameters": parameters,
|
| 737 |
+
}
|
| 738 |
+
|
| 739 |
+
if export_dir:
|
| 740 |
+
path = os.path.join(export_dir, f"{export_name}-{split_name}", "predictions.jsonl")
|
| 741 |
+
write_predictions(path, eval_set["rows"], scores, results, tasks)
|
| 742 |
+
|
| 743 |
+
# Release the GPU before training starts.
|
| 744 |
+
del classifier
|
| 745 |
+
if torch.cuda.is_available():
|
| 746 |
+
torch.cuda.empty_cache()
|
| 747 |
+
|
| 748 |
+
return metrics_by_split
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
# The smallest Jobs flavor for each GPU, keyed by a fragment of the GPU's name. "L40" comes
|
| 752 |
+
# before "L4" because the first match wins.
|
| 753 |
+
GPU_NAME_TO_FLAVOR = {"T4": "t4-small", "A10G": "a10g-small", "L40": "l40sx1", "L4": "l4x1", "A100": "a100-large"}
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
def jobs_flavor() -> str:
|
| 757 |
+
"""Return the Jobs hardware flavor, or "" when it is not known.
|
| 758 |
+
|
| 759 |
+
The docs say ACCELERATOR holds the flavor ("a10g-small"). On the t4-small and a10g-small
|
| 760 |
+
jobs that tested this script it held a bare "gpu", which is not a valid --flavor. So use
|
| 761 |
+
ACCELERATOR when it looks like a flavor, and otherwise name the smallest flavor that has
|
| 762 |
+
this GPU. A larger flavor of the same GPU reproduces the same result.
|
| 763 |
+
"""
|
| 764 |
+
hardware = os.environ.get("ACCELERATOR") or ""
|
| 765 |
+
looks_like_flavor = "-" in hardware or any(character.isdigit() for character in hardware)
|
| 766 |
+
if looks_like_flavor:
|
| 767 |
+
return hardware
|
| 768 |
+
if not torch.cuda.is_available():
|
| 769 |
+
return ""
|
| 770 |
+
gpu_name = torch.cuda.get_device_name(0)
|
| 771 |
+
for fragment, flavor in GPU_NAME_TO_FLAVOR.items():
|
| 772 |
+
if fragment in gpu_name:
|
| 773 |
+
return flavor
|
| 774 |
+
return ""
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
def build_reproduce_command(args) -> str:
|
| 778 |
+
"""Rebuild the exact invocation, so the card's command produces the card's model."""
|
| 779 |
+
flavor = jobs_flavor() or "t4-small"
|
| 780 |
+
# The timeout is the [tool.hf-jobs] default, spelled out because older CLIs ignore the header.
|
| 781 |
+
parts = [f"hf jobs uv run --flavor {flavor} --timeout 1h --secrets HF_TOKEN \\"]
|
| 782 |
+
if args.train_file:
|
| 783 |
+
# Local files: the job needs them mounted at the same paths.
|
| 784 |
+
parts.insert(0, "# Mount the data files at the paths below, e.g. -v hf://buckets/<owner>/<bucket>:/bucket")
|
| 785 |
+
positionals = [shlex.quote(value) for value in (args.input_dataset, args.output_repo) if value]
|
| 786 |
+
if positionals:
|
| 787 |
+
parts.append(f" {SCRIPT_URL} \\")
|
| 788 |
+
parts.append(" " + " ".join(positionals))
|
| 789 |
+
else:
|
| 790 |
+
parts.append(f" {SCRIPT_URL}")
|
| 791 |
+
flags = []
|
| 792 |
+
if args.train_file:
|
| 793 |
+
flags.append(f"--train-file {shlex.quote(args.train_file)}")
|
| 794 |
+
for name, path in args.eval_files.items():
|
| 795 |
+
flags.append(f"--eval-file {shlex.quote(f'{name}={path}')}")
|
| 796 |
+
if args.labels_file:
|
| 797 |
+
flags.append(f"--labels-file {shlex.quote(args.labels_file)}")
|
| 798 |
+
if args.dataset_config:
|
| 799 |
+
flags.append(f"--dataset-config {shlex.quote(args.dataset_config)}")
|
| 800 |
+
if args.text_column != "text":
|
| 801 |
+
flags.append(f"--text-column {shlex.quote(args.text_column)}")
|
| 802 |
+
if args.label_column != ["label"]:
|
| 803 |
+
for column in args.label_column:
|
| 804 |
+
flags.append(f"--label-column {shlex.quote(column)}")
|
| 805 |
+
if args.task_name != args.label_column:
|
| 806 |
+
for task_name in args.task_name:
|
| 807 |
+
flags.append(f"--task-name {shlex.quote(task_name)}")
|
| 808 |
+
if args.base_model != DEFAULT_BASE_MODEL:
|
| 809 |
+
flags.append(f"--base-model {shlex.quote(args.base_model)}")
|
| 810 |
+
if args.train_split != "train":
|
| 811 |
+
flags.append(f"--train-split {shlex.quote(args.train_split)}")
|
| 812 |
+
if args.eval_split:
|
| 813 |
+
flags.append(f"--eval-split {shlex.quote(args.eval_split)}")
|
| 814 |
+
# These change which rows are trained on or scored, so a command without them reproduces
|
| 815 |
+
# a different model and a different number.
|
| 816 |
+
if args.eval_fraction != 0.1:
|
| 817 |
+
flags.append(f"--eval-fraction {args.eval_fraction}")
|
| 818 |
+
if args.max_train_samples:
|
| 819 |
+
flags.append(f"--max-train-samples {args.max_train_samples}")
|
| 820 |
+
if args.max_eval_samples != 2000:
|
| 821 |
+
flags.append(f"--max-eval-samples {args.max_eval_samples}")
|
| 822 |
+
if args.max_text_chars != 2000:
|
| 823 |
+
flags.append(f"--max-text-chars {args.max_text_chars}")
|
| 824 |
+
if args.epochs != 5:
|
| 825 |
+
flags.append(f"--epochs {args.epochs}")
|
| 826 |
+
if args.batch_size != 16:
|
| 827 |
+
flags.append(f"--batch-size {args.batch_size}")
|
| 828 |
+
if args.grad_accum != 1:
|
| 829 |
+
flags.append(f"--grad-accum {args.grad_accum}")
|
| 830 |
+
if args.encoder_lr != 1e-5:
|
| 831 |
+
flags.append(f"--encoder-lr {args.encoder_lr}")
|
| 832 |
+
if args.task_lr != 5e-4:
|
| 833 |
+
flags.append(f"--task-lr {args.task_lr}")
|
| 834 |
+
if args.seed != 42:
|
| 835 |
+
flags.append(f"--seed {args.seed}")
|
| 836 |
+
if args.precision != "auto":
|
| 837 |
+
flags.append(f"--precision {args.precision}")
|
| 838 |
+
if args.skip_zero_shot:
|
| 839 |
+
flags.append("--skip-zero-shot")
|
| 840 |
+
if args.label_augmentation != "upstream":
|
| 841 |
+
flags.append(f"--label-augmentation {args.label_augmentation}")
|
| 842 |
+
if args.no_push:
|
| 843 |
+
flags.append(f"--no-push --output-dir {shlex.quote(args.output_dir)}")
|
| 844 |
+
if args.export_predictions:
|
| 845 |
+
flags.append(f"--export-predictions {shlex.quote(args.export_predictions)}")
|
| 846 |
+
if args.public:
|
| 847 |
+
flags.append("--public")
|
| 848 |
+
|
| 849 |
+
if flags:
|
| 850 |
+
parts[-1] += " \\"
|
| 851 |
+
parts.append(" " + " ".join(flags))
|
| 852 |
+
return "\n".join(parts)
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
def results_table(tasks: list, zero_shot, fine_tuned) -> str:
|
| 856 |
+
"""One row per task and metric, with the zero-shot score next to the fine-tuned one."""
|
| 857 |
+
lines = ["| Task | Metric | Zero-shot | Fine-tuned |", "|---|---|---|---|"]
|
| 858 |
+
for task in tasks:
|
| 859 |
+
name = task["name"]
|
| 860 |
+
for metric, value in fine_tuned["tasks"][name].items():
|
| 861 |
+
if metric == "majority_baseline":
|
| 862 |
+
continue
|
| 863 |
+
before = zero_shot["tasks"][name][metric] if zero_shot else "not run"
|
| 864 |
+
lines.append(f"| `{name}` | {metric} | {before} | **{value}** |")
|
| 865 |
+
return "\n".join(lines)
|
| 866 |
+
|
| 867 |
+
|
| 868 |
+
def build_card(args, tasks, zero_shot, fine_tuned, train_size, train_seconds, carved_out, oom_steps) -> str:
|
| 869 |
+
"""Model card following the uv-scripts conventions (org credit, Jobs claim gated on JOB_ID)."""
|
| 870 |
+
on_jobs = os.environ.get("JOB_ID") is not None
|
| 871 |
+
hardware = jobs_flavor()
|
| 872 |
+
if on_jobs:
|
| 873 |
+
provenance = "Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"
|
| 874 |
+
if hardware:
|
| 875 |
+
provenance += f" (`{hardware}`)"
|
| 876 |
+
else:
|
| 877 |
+
provenance = "Produced"
|
| 878 |
+
provenance += " with [`uv-scripts/classification`](https://huggingface.co/datasets/uv-scripts/classification)."
|
| 879 |
+
|
| 880 |
+
tags = ["gliner2", "text-classification", "uv-script"]
|
| 881 |
+
if on_jobs:
|
| 882 |
+
tags.append("hf-jobs")
|
| 883 |
+
tag_lines = "\n".join(f"- {tag}" for tag in tags)
|
| 884 |
+
|
| 885 |
+
caveats = []
|
| 886 |
+
if carved_out:
|
| 887 |
+
caveats.append(
|
| 888 |
+
f"**No held-out split existed, so {args.eval_fraction:.0%} was carved out of train.** "
|
| 889 |
+
"These numbers are not comparable with published results on this dataset."
|
| 890 |
+
)
|
| 891 |
+
for split_name, split_metrics in fine_tuned.items():
|
| 892 |
+
for task in tasks:
|
| 893 |
+
if not task["multi_label"]:
|
| 894 |
+
floor = split_metrics["tasks"][task["name"]]["majority_baseline"]
|
| 895 |
+
caveats.append(
|
| 896 |
+
f"`{task['name']}` on `{split_name}`: always answering the most common label scores "
|
| 897 |
+
f"`{floor}` accuracy. Read the accuracy against that floor."
|
| 898 |
+
)
|
| 899 |
+
if oom_steps:
|
| 900 |
+
caveats.append(
|
| 901 |
+
f"**{oom_steps} training step(s) were skipped** because the GPU ran out of memory. "
|
| 902 |
+
"The model saw less data than the example count above suggests."
|
| 903 |
+
)
|
| 904 |
+
caveats.append("Single seed. Small differences between runs are not evidence of anything.")
|
| 905 |
+
caveat_block = "\n".join(f"- {caveat}" for caveat in caveats)
|
| 906 |
+
|
| 907 |
+
label_lines = []
|
| 908 |
+
for task in tasks:
|
| 909 |
+
kind = "multi-label" if task["multi_label"] else "single-label"
|
| 910 |
+
names = ", ".join(f"`{label}`" for label in task["labels"])
|
| 911 |
+
label_lines.append(f"- **`{task['name']}`** ({kind}): {names}")
|
| 912 |
+
label_block = "\n".join(label_lines)
|
| 913 |
+
|
| 914 |
+
schema_lines = ["schema = ClassificationSchema()"]
|
| 915 |
+
for task in tasks:
|
| 916 |
+
method = "multi" if task["multi_label"] else "single"
|
| 917 |
+
schema_lines.append(f"schema.{method}({task['name']!r}, {task['labels']!r})")
|
| 918 |
+
schema_code = "\n".join(schema_lines)
|
| 919 |
+
first_task = tasks[0]
|
| 920 |
+
read_result = "selected" if first_task["multi_label"] else "value"
|
| 921 |
+
|
| 922 |
+
result_sections = []
|
| 923 |
+
for split_name, split_metrics in fine_tuned.items():
|
| 924 |
+
split_zero_shot = zero_shot[split_name] if zero_shot else None
|
| 925 |
+
result_sections.append(
|
| 926 |
+
f"`{split_name}`: {split_metrics['eval_examples']} held-out examples.\n\n"
|
| 927 |
+
+ results_table(tasks, split_zero_shot, split_metrics)
|
| 928 |
+
)
|
| 929 |
+
result_block = "\n\n".join(result_sections)
|
| 930 |
+
|
| 931 |
+
first_split = next(iter(fine_tuned.values()))
|
| 932 |
+
size = f"{first_split['parameters'] / 1e6:.0f}M parameters"
|
| 933 |
+
if args.input_dataset:
|
| 934 |
+
source = f"[`{args.input_dataset}`](https://huggingface.co/datasets/{args.input_dataset})"
|
| 935 |
+
dataset_metadata = f"datasets:\n- {args.input_dataset}\n"
|
| 936 |
+
else:
|
| 937 |
+
source = f"the local file `{os.path.basename(args.train_file)}`"
|
| 938 |
+
dataset_metadata = ""
|
| 939 |
+
if args.output_repo:
|
| 940 |
+
title = args.output_repo.split("/")[-1]
|
| 941 |
+
model_ref = args.output_repo
|
| 942 |
+
else:
|
| 943 |
+
title = os.path.basename(os.path.abspath(args.output_dir))
|
| 944 |
+
model_ref = os.path.join(args.output_dir, "final")
|
| 945 |
+
|
| 946 |
+
return f"""---
|
| 947 |
+
tags:
|
| 948 |
+
{tag_lines}
|
| 949 |
+
library_name: gliner2
|
| 950 |
+
pipeline_tag: text-classification
|
| 951 |
+
base_model: {args.base_model}
|
| 952 |
+
{dataset_metadata}---
|
| 953 |
+
|
| 954 |
+
# {title}
|
| 955 |
+
|
| 956 |
+
[GLiNER2](https://github.com/fastino-ai/GLiNER2) text classifier ({size}), fine-tuned from
|
| 957 |
+
[`{args.base_model}`](https://huggingface.co/{args.base_model}) on {train_size} examples from
|
| 958 |
+
{source}.
|
| 959 |
+
|
| 960 |
+
{provenance}
|
| 961 |
+
|
| 962 |
+
## Results
|
| 963 |
+
|
| 964 |
+
"Zero-shot" is the base model given only the label names, before any training, on the same
|
| 965 |
+
examples.
|
| 966 |
+
|
| 967 |
+
{result_block}
|
| 968 |
+
|
| 969 |
+
Training took {round(train_seconds)} seconds.
|
| 970 |
+
|
| 971 |
+
## Read this before trusting the numbers
|
| 972 |
+
|
| 973 |
+
{caveat_block}
|
| 974 |
+
|
| 975 |
+
## Tasks and labels
|
| 976 |
+
|
| 977 |
+
{label_block}
|
| 978 |
+
|
| 979 |
+
## Use it
|
| 980 |
+
|
| 981 |
+
```python
|
| 982 |
+
# pip install "gliner2[local]==2.0.0" protobuf sentencepiece
|
| 983 |
+
from gliner2.classification import ClassificationSchema, Classifier
|
| 984 |
+
|
| 985 |
+
classifier = Classifier.from_pretrained("{model_ref}").eval()
|
| 986 |
+
|
| 987 |
+
{schema_code}
|
| 988 |
+
|
| 989 |
+
result = classifier.batch_classify(["some text to classify"], schema)[0]
|
| 990 |
+
print(result.{read_result}({first_task["name"]!r}), result.confidence({first_task["name"]!r}))
|
| 991 |
+
```
|
| 992 |
+
|
| 993 |
+
To label a whole Hub dataset with this model:
|
| 994 |
+
|
| 995 |
+
```bash
|
| 996 |
+
hf jobs uv run --flavor t4-small --timeout 1h --secrets HF_TOKEN \\
|
| 997 |
+
https://huggingface.co/datasets/uv-scripts/classification/raw/main/classify-gliner2.py \\
|
| 998 |
+
<input-dataset> <output-dataset> --model {shlex.quote(model_ref)} --text-column {shlex.quote(args.text_column)}
|
| 999 |
+
```
|
| 1000 |
+
|
| 1001 |
+
## Reproduction
|
| 1002 |
+
|
| 1003 |
+
Produced by [`train-gliner2.py`]({SCRIPT_URL}) from
|
| 1004 |
+
[`uv-scripts/classification`](https://huggingface.co/datasets/uv-scripts/classification):
|
| 1005 |
+
|
| 1006 |
+
```bash
|
| 1007 |
+
{build_reproduce_command(args)}
|
| 1008 |
+
```
|
| 1009 |
+
"""
|
| 1010 |
+
|
| 1011 |
+
|
| 1012 |
+
def ensure_output_repo(api: HfApi, repo_id: str, private: bool) -> None:
|
| 1013 |
+
"""Create the model repo, and refuse to train if a private run would push to a public repo.
|
| 1014 |
+
|
| 1015 |
+
create_repo(exist_ok=True) leaves an existing repo's visibility alone, so a repo that
|
| 1016 |
+
already exists as public would silently receive a "private" model.
|
| 1017 |
+
"""
|
| 1018 |
+
api.create_repo(repo_id, repo_type="model", private=private, exist_ok=True)
|
| 1019 |
+
if private and not api.repo_info(repo_id, repo_type="model").private:
|
| 1020 |
+
sys.exit(
|
| 1021 |
+
f"{repo_id} already exists and is public. Pass --public to push there anyway, or choose "
|
| 1022 |
+
"a new repo name."
|
| 1023 |
+
)
|
| 1024 |
+
|
| 1025 |
+
|
| 1026 |
+
def main(args) -> None:
|
| 1027 |
+
token = args.hf_token or os.environ.get("HF_TOKEN")
|
| 1028 |
+
if token:
|
| 1029 |
+
login(token=token)
|
| 1030 |
+
elif not args.no_push:
|
| 1031 |
+
sys.exit("No HF token. Pass --hf-token or run with --secrets HF_TOKEN (or pass --no-push).")
|
| 1032 |
+
|
| 1033 |
+
if not torch.cuda.is_available():
|
| 1034 |
+
if not args.allow_cpu:
|
| 1035 |
+
sys.exit(
|
| 1036 |
+
"No GPU found. GLiNER2 fine-tuning needs one: run with `--flavor t4-small` on HF "
|
| 1037 |
+
"Jobs. Pass --allow-cpu to run anyway (only sensible with a tiny --max-train-samples)."
|
| 1038 |
+
)
|
| 1039 |
+
logger.warning("No GPU found; training on CPU because --allow-cpu was passed.")
|
| 1040 |
+
else:
|
| 1041 |
+
logger.info(
|
| 1042 |
+
"GPU: %s (ACCELERATOR=%s)", torch.cuda.get_device_name(0), os.environ.get("ACCELERATOR")
|
| 1043 |
+
)
|
| 1044 |
+
|
| 1045 |
+
# Prove we can write the output repo BEFORE paying for training.
|
| 1046 |
+
api = HfApi(token=token)
|
| 1047 |
+
if args.no_push:
|
| 1048 |
+
logger.info("--no-push: the model will stay in %s.", os.path.join(args.output_dir, "final"))
|
| 1049 |
+
else:
|
| 1050 |
+
ensure_output_repo(api, args.output_repo, private=not args.public)
|
| 1051 |
+
|
| 1052 |
+
precision = resolve_precision(args.precision)
|
| 1053 |
+
sampling_config = resolve_sampling_config(args.label_augmentation)
|
| 1054 |
+
manifest = build_manifest(args, sampling_config, precision)
|
| 1055 |
+
manifest_dirs = [args.output_dir]
|
| 1056 |
+
if args.export_predictions:
|
| 1057 |
+
manifest_dirs.append(args.export_predictions)
|
| 1058 |
+
# Written now, so a run that dies still records what it was; rewritten with results at the end.
|
| 1059 |
+
write_manifest(manifest, manifest_dirs)
|
| 1060 |
+
|
| 1061 |
+
train_data, raw_eval_sets, carved_out = load_splits(args)
|
| 1062 |
+
|
| 1063 |
+
for split_name, data in [("train", train_data)] + list(raw_eval_sets.items()):
|
| 1064 |
+
for column in [args.text_column] + args.label_column:
|
| 1065 |
+
if column not in data.column_names:
|
| 1066 |
+
sys.exit(f"Column '{column}' not found in '{split_name}'. Columns are: {data.column_names}.")
|
| 1067 |
+
|
| 1068 |
+
train_data = drop_unlabelled_rows(train_data, args.label_column, args.text_column, "train")
|
| 1069 |
+
if args.max_train_samples and len(train_data) > args.max_train_samples:
|
| 1070 |
+
train_data = train_data.shuffle(seed=args.seed).select(range(args.max_train_samples))
|
| 1071 |
+
logger.info("Train examples: %d.", len(train_data))
|
| 1072 |
+
|
| 1073 |
+
fixed_labels = load_labels_file(args.labels_file) if args.labels_file else None
|
| 1074 |
+
tasks = build_tasks(train_data, args.label_column, args.task_name, fixed_labels)
|
| 1075 |
+
train_texts = prepare_texts(train_data, args.text_column, args.max_text_chars, "train")
|
| 1076 |
+
train_gold = {task["name"]: decode_column(train_data, task["column"]) for task in tasks}
|
| 1077 |
+
logger.info("Example input: %s", train_texts[0][:300])
|
| 1078 |
+
|
| 1079 |
+
# Local eval files, and any eval split whose predictions are exported, are scored in full
|
| 1080 |
+
# and in order. Only a Hub eval split that is not exported keeps the old shuffled cap.
|
| 1081 |
+
full_eval = bool(args.train_file or args.export_predictions)
|
| 1082 |
+
eval_sets = {}
|
| 1083 |
+
for split_name, data in raw_eval_sets.items():
|
| 1084 |
+
data = add_row_numbers(data)
|
| 1085 |
+
data = drop_unlabelled_rows(data, args.label_column, args.text_column, split_name)
|
| 1086 |
+
if not full_eval and len(data) > args.max_eval_samples:
|
| 1087 |
+
data = data.shuffle(seed=args.seed).select(range(args.max_eval_samples))
|
| 1088 |
+
eval_sets[split_name] = {
|
| 1089 |
+
"texts": prepare_texts(data, args.text_column, args.max_text_chars, split_name),
|
| 1090 |
+
"gold": {task["name"]: decode_column(data, task["column"]) for task in tasks},
|
| 1091 |
+
"rows": list(data[ROW_COLUMN]),
|
| 1092 |
+
}
|
| 1093 |
+
logger.info("Eval split '%s': %d examples.", split_name, len(data))
|
| 1094 |
+
|
| 1095 |
+
if fixed_labels is not None:
|
| 1096 |
+
gold_by_split = {"train": train_gold}
|
| 1097 |
+
for split_name, eval_set in eval_sets.items():
|
| 1098 |
+
gold_by_split[split_name] = eval_set["gold"]
|
| 1099 |
+
check_labels_in_set(tasks, gold_by_split)
|
| 1100 |
+
|
| 1101 |
+
zero_shot = None
|
| 1102 |
+
if not args.skip_zero_shot:
|
| 1103 |
+
logger.info("Scoring the base model zero-shot, before any training.")
|
| 1104 |
+
zero_shot = evaluate(
|
| 1105 |
+
args.base_model, eval_sets, tasks, args.eval_batch_size, args.export_predictions, "base"
|
| 1106 |
+
)
|
| 1107 |
+
for split_name, split_metrics in zero_shot.items():
|
| 1108 |
+
logger.info("Zero-shot on '%s': %s", split_name, json.dumps(split_metrics["tasks"]))
|
| 1109 |
+
|
| 1110 |
+
examples = build_training_examples(train_texts, train_gold, tasks)
|
| 1111 |
+
logger.info("Training precision: %s", precision)
|
| 1112 |
+
logger.info("Training for %d epochs on %d examples.", args.epochs, len(examples))
|
| 1113 |
+
started = time.time()
|
| 1114 |
+
oom_steps = train_with_batch_fallback(args, examples, precision, sampling_config)
|
| 1115 |
+
train_seconds = time.time() - started
|
| 1116 |
+
logger.info("Training took %.0f seconds.", train_seconds)
|
| 1117 |
+
if oom_steps:
|
| 1118 |
+
logger.warning(
|
| 1119 |
+
"%d training step(s) were skipped after running out of GPU memory. The model trained "
|
| 1120 |
+
"on the rest. Lower --batch-size to avoid this.", oom_steps,
|
| 1121 |
+
)
|
| 1122 |
+
|
| 1123 |
+
# Score the checkpoint that will actually be uploaded.
|
| 1124 |
+
final_dir = os.path.join(args.output_dir, "final")
|
| 1125 |
+
fine_tuned = evaluate(
|
| 1126 |
+
final_dir, eval_sets, tasks, args.eval_batch_size, args.export_predictions, "finetuned"
|
| 1127 |
+
)
|
| 1128 |
+
for split_name, split_metrics in fine_tuned.items():
|
| 1129 |
+
logger.info("Fine-tuned on '%s': %s", split_name, json.dumps(split_metrics["tasks"]))
|
| 1130 |
+
|
| 1131 |
+
schema_record = {
|
| 1132 |
+
"text_column": args.text_column,
|
| 1133 |
+
"tasks": [
|
| 1134 |
+
{"name": task["name"], "labels": task["labels"], "multi_label": task["multi_label"]}
|
| 1135 |
+
for task in tasks
|
| 1136 |
+
],
|
| 1137 |
+
}
|
| 1138 |
+
with open(os.path.join(final_dir, SCHEMA_FILENAME), "w") as handle:
|
| 1139 |
+
json.dump(schema_record, handle, indent=2)
|
| 1140 |
+
card = build_card(
|
| 1141 |
+
args, tasks, zero_shot, fine_tuned, len(examples), train_seconds, carved_out, oom_steps
|
| 1142 |
+
)
|
| 1143 |
+
with open(os.path.join(final_dir, "README.md"), "w") as handle:
|
| 1144 |
+
handle.write(card)
|
| 1145 |
+
|
| 1146 |
+
summary = {"zero_shot": zero_shot, "fine_tuned": fine_tuned, "train_seconds": round(train_seconds)}
|
| 1147 |
+
manifest["tasks"] = schema_record["tasks"]
|
| 1148 |
+
manifest["train_examples"] = len(examples)
|
| 1149 |
+
manifest["oom_steps"] = oom_steps
|
| 1150 |
+
manifest["results"] = summary
|
| 1151 |
+
write_manifest(manifest, manifest_dirs + [final_dir])
|
| 1152 |
+
|
| 1153 |
+
if args.no_push:
|
| 1154 |
+
logger.info("--no-push: nothing uploaded. The model is in %s", final_dir)
|
| 1155 |
+
else:
|
| 1156 |
+
api.upload_folder(repo_id=args.output_repo, folder_path=final_dir, repo_type="model")
|
| 1157 |
+
logger.info("Pushed to https://huggingface.co/%s", args.output_repo)
|
| 1158 |
+
print("SUMMARY_JSON " + json.dumps(summary))
|
| 1159 |
+
|
| 1160 |
+
|
| 1161 |
+
def parse_eval_files(values: list) -> dict:
|
| 1162 |
+
"""Turn repeated --eval-file NAME=PATH values into {name: path}, in the order given."""
|
| 1163 |
+
eval_files = {}
|
| 1164 |
+
for value in values or []:
|
| 1165 |
+
name, separator, path = value.partition("=")
|
| 1166 |
+
name = name.strip()
|
| 1167 |
+
if not separator or not name or not path:
|
| 1168 |
+
sys.exit(f"--eval-file wants NAME=PATH, got {value!r}.")
|
| 1169 |
+
if "/" in name or name in eval_files:
|
| 1170 |
+
sys.exit(f"--eval-file name {name!r} must be unique and contain no '/'.")
|
| 1171 |
+
eval_files[name] = path
|
| 1172 |
+
return eval_files
|
| 1173 |
+
|
| 1174 |
+
|
| 1175 |
+
def parse_args():
|
| 1176 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 1177 |
+
parser.add_argument(
|
| 1178 |
+
"input_dataset", nargs="?",
|
| 1179 |
+
help="Input dataset ID. Leave out with --train-file; a single positional is then the output repo.",
|
| 1180 |
+
)
|
| 1181 |
+
parser.add_argument("output_repo", nargs="?", help="Output model repo ID (username/model-name). Not needed with --no-push.")
|
| 1182 |
+
parser.add_argument("--train-file", help="Train on a local JSON Lines file (e.g. under a mounted /bucket) instead of a Hub dataset")
|
| 1183 |
+
parser.add_argument(
|
| 1184 |
+
"--eval-file", action="append",
|
| 1185 |
+
help="NAME=PATH of a local JSON Lines eval split. Repeat for several splits. Scored in full, in file order.",
|
| 1186 |
+
)
|
| 1187 |
+
parser.add_argument(
|
| 1188 |
+
"--labels-file",
|
| 1189 |
+
help="Fixed label set (a JSON list, or one label per line), used in this order for training, "
|
| 1190 |
+
"zero-shot and eval. Every label in the data must be in it. Needs exactly one --label-column.",
|
| 1191 |
+
)
|
| 1192 |
+
parser.add_argument("--base-model", default=DEFAULT_BASE_MODEL, help=f"GLiNER2 checkpoint to start from (default: {DEFAULT_BASE_MODEL})")
|
| 1193 |
+
parser.add_argument("--dataset-config", help="Dataset config name")
|
| 1194 |
+
parser.add_argument("--text-column", default="text", help="Text column (default: text)")
|
| 1195 |
+
parser.add_argument(
|
| 1196 |
+
"--label-column", action="append",
|
| 1197 |
+
help="Label column (default: label). Repeat for several tasks in one model. A column of "
|
| 1198 |
+
"lists is treated as multi-label.",
|
| 1199 |
+
)
|
| 1200 |
+
parser.add_argument(
|
| 1201 |
+
"--task-name", action="append",
|
| 1202 |
+
help="Name of the task, one per --label-column in the same order (default: the column "
|
| 1203 |
+
"name). The model reads it as part of its prompt, and it names the output columns.",
|
| 1204 |
+
)
|
| 1205 |
+
parser.add_argument("--train-split", default="train", help="Train split (default: train)")
|
| 1206 |
+
parser.add_argument("--eval-split", help="Eval split (default: validation or test if present, else a carve-out of train)")
|
| 1207 |
+
parser.add_argument("--eval-fraction", type=float, default=0.1, help="Eval fraction if no eval split (default: 0.1)")
|
| 1208 |
+
parser.add_argument("--max-train-samples", type=int, help="Cap training examples (smoke runs)")
|
| 1209 |
+
parser.add_argument(
|
| 1210 |
+
"--max-eval-samples", type=int, default=2000,
|
| 1211 |
+
help="Cap Hub eval examples (default: 2000). Not applied to --eval-file splits or with --export-predictions.",
|
| 1212 |
+
)
|
| 1213 |
+
parser.add_argument("--max-text-chars", type=int, default=2000, help="Truncate texts to this many characters (default: 2000)")
|
| 1214 |
+
parser.add_argument("--epochs", type=int, default=5, help="Epochs (default: 5)")
|
| 1215 |
+
parser.add_argument("--batch-size", type=int, default=16, help="Training batch size (default: 16)")
|
| 1216 |
+
parser.add_argument("--eval-batch-size", type=int, default=32, help="Prediction batch size (default: 32)")
|
| 1217 |
+
parser.add_argument("--grad-accum", type=int, default=1, help="Gradient accumulation steps (default: 1)")
|
| 1218 |
+
parser.add_argument("--encoder-lr", type=float, default=1e-5, help="Encoder learning rate (default: 1e-5)")
|
| 1219 |
+
parser.add_argument("--task-lr", type=float, default=5e-4, help="Task-head learning rate (default: 5e-4)")
|
| 1220 |
+
parser.add_argument("--seed", type=int, default=42, help="Seed (default: 42)")
|
| 1221 |
+
parser.add_argument(
|
| 1222 |
+
"--precision", choices=["auto", "fp32", "bf16"], default="auto",
|
| 1223 |
+
help="Training precision (default: auto = bf16 on Ampere or newer GPUs such as A10G and L4, fp32 on T4 and CPU)",
|
| 1224 |
+
)
|
| 1225 |
+
parser.add_argument(
|
| 1226 |
+
"--label-augmentation", choices=["upstream", "off"], default="upstream",
|
| 1227 |
+
help="upstream (default) = gliner2's synthetic label names and label dropping during training; "
|
| 1228 |
+
"off = always train on the real, complete label set (for a fixed schema)",
|
| 1229 |
+
)
|
| 1230 |
+
|
| 1231 |
+
parser.add_argument("--skip-zero-shot", action="store_true", help="Skip the zero-shot score of the base model")
|
| 1232 |
+
parser.add_argument("--allow-cpu", action="store_true", help="Train without a GPU (slow)")
|
| 1233 |
+
parser.add_argument("--output-dir", default="./output", help="Local checkpoint directory; the model is saved in <dir>/final (default: ./output)")
|
| 1234 |
+
parser.add_argument(
|
| 1235 |
+
"--export-predictions",
|
| 1236 |
+
help="Directory for per-row predictions: <dir>/{base,finetuned}-<split>/predictions.jsonl",
|
| 1237 |
+
)
|
| 1238 |
+
parser.add_argument("--no-push", action="store_true", help="Do not create or upload a Hub repo; keep the model in --output-dir")
|
| 1239 |
+
parser.add_argument("--public", action="store_true", help="Make the output model repo public (default: private)")
|
| 1240 |
+
parser.add_argument("--private", action="store_true", help="Accepted for older commands; private is now the default")
|
| 1241 |
+
parser.add_argument("--hf-token", help="HF token (or set HF_TOKEN)")
|
| 1242 |
+
args = parser.parse_args()
|
| 1243 |
+
if not args.label_column:
|
| 1244 |
+
args.label_column = ["label"]
|
| 1245 |
+
if not args.task_name:
|
| 1246 |
+
args.task_name = list(args.label_column)
|
| 1247 |
+
if len(args.task_name) != len(args.label_column):
|
| 1248 |
+
parser.error("Pass one --task-name per --label-column, in the same order.")
|
| 1249 |
+
if len(set(args.task_name)) != len(args.task_name):
|
| 1250 |
+
parser.error("Each --task-name must be different.")
|
| 1251 |
+
if args.public and args.private:
|
| 1252 |
+
parser.error("Pass --public or --private, not both.")
|
| 1253 |
+
|
| 1254 |
+
if args.train_file:
|
| 1255 |
+
# With local files there is no input dataset, so one positional is the output repo.
|
| 1256 |
+
if args.input_dataset and not args.output_repo:
|
| 1257 |
+
args.output_repo = args.input_dataset
|
| 1258 |
+
args.input_dataset = None
|
| 1259 |
+
if args.input_dataset:
|
| 1260 |
+
parser.error("Pass either an input dataset or --train-file, not both.")
|
| 1261 |
+
if not args.eval_file:
|
| 1262 |
+
parser.error("--train-file needs at least one --eval-file NAME=PATH.")
|
| 1263 |
+
if args.eval_split or args.dataset_config:
|
| 1264 |
+
parser.error("--eval-split and --dataset-config apply to Hub datasets, not --train-file.")
|
| 1265 |
+
else:
|
| 1266 |
+
if not args.input_dataset:
|
| 1267 |
+
parser.error("Pass an input dataset ID, or --train-file with --eval-file.")
|
| 1268 |
+
if args.eval_file:
|
| 1269 |
+
parser.error("--eval-file needs --train-file.")
|
| 1270 |
+
args.eval_files = parse_eval_files(args.eval_file)
|
| 1271 |
+
if not args.no_push and not args.output_repo:
|
| 1272 |
+
parser.error("Pass an output repo, or --no-push.")
|
| 1273 |
+
if args.labels_file and len(args.label_column) != 1:
|
| 1274 |
+
parser.error("--labels-file needs exactly one --label-column.")
|
| 1275 |
+
return args
|
| 1276 |
+
|
| 1277 |
+
|
| 1278 |
+
if __name__ == "__main__":
|
| 1279 |
+
main(parse_args())
|