Sync from GitHub via hub-sync
Browse files- GLINER2-NOTES.md +11 -0
- README.md +105 -436
- SETFIT-NOTES.md +79 -0
- classify-gliner2.py +11 -1
- train-gliner2.py +11 -3
GLINER2-NOTES.md
CHANGED
|
@@ -99,6 +99,17 @@ How it was set up, if you want to do something similar with your own label list:
|
|
| 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:
|
|
|
|
| 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 |
+
## Choosing a model size
|
| 103 |
+
|
| 104 |
+
| Base model | Params | Use it when | Hub-tags top-1 | CPU latency per row (free Space, 2 vCPU) | GPU (L4, fp16) |
|
| 105 |
+
| -------------------------------------- | ------ | ------------------------------------------ | -------------- | ---------------------------------------- | -------------- |
|
| 106 |
+
| [`fastino/gliner2.5-small-v1`](https://huggingface.co/fastino/gliner2.5-small-v1) | 74M | speed matters most | 0.653 | ~0.3 s | ~19 ms |
|
| 107 |
+
| [`fastino/gliner2.5-base-v1`](https://huggingface.co/fastino/gliner2.5-base-v1) | 194M | English text; the best accuracy per second | 0.690 | ~0.7–1 s | ~19 ms |
|
| 108 |
+
| [`fastino/gliner2.5-multi-v1`](https://huggingface.co/fastino/gliner2.5-multi-v1) (default) | 287M | non-English or mixed-language text | not measured | — | — |
|
| 109 |
+
|
| 110 |
+
On a GPU, base and small are equally fast per row; the difference only shows on a CPU. For speed on
|
| 111 |
+
a CPU, use plain fp32 PyTorch (see below for what did not work).
|
| 112 |
+
|
| 113 |
## Speed and quantization
|
| 114 |
|
| 115 |
Per-row latency at batch size 1, fine-tuned 52-label models:
|
README.md
CHANGED
|
@@ -1,20 +1,41 @@
|
|
| 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
|
| 7 |
|
| 8 |
-
Text classification on [HF Jobs](https://huggingface.co/docs/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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://
|
| 14 |
-
| [`train-setfit.py`](#few-shot-with-setfit-train-setfitpy) | **Few-shot** train a classifier from 8-64 labels per class with [SetFit](https://
|
| 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 |
|
| 19 |
Pick by how many labels you have:
|
| 20 |
|
|
@@ -25,8 +46,9 @@ Pick by how many labels you have:
|
|
| 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,
|
| 29 |
-
dedicated model on what you kept.
|
|
|
|
| 30 |
|
| 31 |
## Zero-shot first, then fine-tune (GLiNER2)
|
| 32 |
|
|
@@ -34,19 +56,20 @@ Label a dataset with your own list of labels, see how far zero-shot gets you, th
|
|
| 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
|
| 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
|
|
|
|
| 50 |
|
| 51 |
### Quick start
|
| 52 |
|
|
@@ -54,19 +77,19 @@ your labels mean in your data. (For entity extraction with the original GLiNER l
|
|
| 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
|
| 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
|
| 64 |
-
--dataset-config title_genre_classifiction --text-column title --model
|
| 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
|
| 70 |
--labels World Sports Business "Science and technology" --task-name topic
|
| 71 |
```
|
| 72 |
|
|
@@ -76,9 +99,12 @@ the model has not seen. Outputs are **private by default** (`--public` to opt ou
|
|
| 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.
|
|
|
|
|
|
|
| 80 |
|
| 81 |
-
|
|
|
|
| 82 |
|
| 83 |
| Dataset | Task | Labels | Train rows × epochs | Train time | Train cost | Metric | Majority floor | Zero-shot | Fine-tuned |
|
| 84 |
|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -93,18 +119,6 @@ English text, `--base-model fastino/gliner2.5-base-v1` is smaller and faster;
|
|
| 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
|
|
@@ -116,8 +130,13 @@ For tens of labels scored together (a taxonomy, a fixed tag list), or data in a
|
|
| 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,
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
### Good to know
|
| 123 |
|
|
@@ -132,7 +151,7 @@ More behaviour details, tested commands, findings and dead ends: [GLINER2-NOTES.
|
|
| 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://
|
| 136 |
examples per class. SetFit finetunes a sentence-transformer body on contrastive pairs, then fits a
|
| 137 |
logistic regression head on the resulting embeddings.
|
| 138 |
|
|
@@ -140,16 +159,6 @@ logistic regression head on the resulting embeddings.
|
|
| 140 |
training, particularly with larger models, longer texts or more classes. The same model and
|
| 141 |
training settings work on either; the recipe uses the available accelerator automatically.
|
| 142 |
|
| 143 |
-
- **Default body**: [`all-MiniLM-L6-v2`](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) (22M), chosen for CPU speed. Swap it with `--body-model`.
|
| 144 |
-
- **Evaluation split** follows the same precedence as `train-classifier.py`: `--eval-split` if given, else `validation`, else `test`, else a stratified carve-out of `--eval-fraction` from train.
|
| 145 |
-
- **Single-label only.** A multi-label column exits with a pointer to `train-classifier.py`.
|
| 146 |
-
- **Metrics match `train-classifier.py`** (accuracy + macro F1). Match evaluation rows and preprocessing when comparing runs.
|
| 147 |
-
- **`--num-samples`** sets labelled examples per class (default 8). **`--sampling-strategy`** controls contrastive pairing: `oversampling` (default), `undersampling`, `unique`.
|
| 148 |
-
- **Every run reports a majority baseline.** The run warns when accuracy fails to beat it, or the gain is below five percentage points. That fixed threshold is a review heuristic, not a measured noise level or significance test.
|
| 149 |
-
- **It estimates training time before starting.** The script times forward/backward passes on actual texts and hardware, then refuses training projected above `--max-minutes` (default 60). Setup, evaluation and upload take additional time. A measurement error can skip this guard; use Jobs `--timeout` to enforce a wall-clock limit.
|
| 150 |
-
- **Rows with missing or blank labels or texts are dropped**, with a count. Missing labels include `ClassLabel`'s `-1` sentinel and numeric NaN; plain integer `-1` remains a valid class. Splits with no usable labelled text, fewer than two observed training classes, and missing or non-string text columns exit before model loading.
|
| 151 |
-
- **`--private` verifies the output repository is private before training.** If the destination already exists publicly, choose a new repo or change its visibility first.
|
| 152 |
-
|
| 153 |
```bash
|
| 154 |
# 8 labels per class, on CPU
|
| 155 |
hf jobs uv run --flavor cpu-basic --timeout 20m --secrets HF_TOKEN \
|
|
@@ -162,19 +171,6 @@ hf jobs uv run --flavor t4-small --timeout 20m --secrets HF_TOKEN \
|
|
| 162 |
fancyzhx/ag_news username/ag-news-setfit-gpu --num-samples 8
|
| 163 |
```
|
| 164 |
|
| 165 |
-
### Choosing another body or longer context
|
| 166 |
-
|
| 167 |
-
`--body-model` accepts a Sentence Transformer checkpoint. Set `--max-seq-length` within that
|
| 168 |
-
model's supported context window; increasing it cannot extend a model's native limit or restore
|
| 169 |
-
text already shortened during dataset preparation. Longer sequences can need a smaller
|
| 170 |
-
`--batch-size` or more GPU memory. The recipe measures training cost on the selected hardware.
|
| 171 |
-
|
| 172 |
-
Follow the body's task-prefix instructions when preparing inputs. For example,
|
| 173 |
-
[`nomic-ai/modernbert-embed-base`](https://huggingface.co/nomic-ai/modernbert-embed-base)
|
| 174 |
-
uses Nomic's task prefixes: classification inputs should begin with `classification: `.
|
| 175 |
-
Include the same prefix during training, evaluation and inference. The recipe does not add it
|
| 176 |
-
automatically. Retain the original texts and the preprocessing details with the model.
|
| 177 |
-
|
| 178 |
### Measured
|
| 179 |
|
| 180 |
8 labels per class, seed 42, evaluated on each dataset's own held-out split (capped at 500
|
|
@@ -192,67 +188,23 @@ substantially with which examples happen to get sampled; SetFit's own benchmarks
|
|
| 192 |
standard deviation across ten seeds for exactly this reason. Run your own task before trusting
|
| 193 |
any of these numbers.
|
| 194 |
|
| 195 |
-
###
|
| 196 |
-
|
| 197 |
-
The `emotion` run reached **0.370** accuracy against a **0.352** majority baseline. Other
|
| 198 |
-
single-seed body-model runs reached 0.418 (`bge-small`) and 0.410 (`paraphrase-mpnet-base-v2`).
|
| 199 |
-
These results call for further evaluation; they do not establish a limit on the task or method.
|
| 200 |
-
|
| 201 |
-
SetFit's [zero-shot guide](https://huggingface.co/docs/setfit/how_to/zero_shot) reports **0.591**
|
| 202 |
-
on emotion using BGE and training examples templated from the class names. It uses a different
|
| 203 |
-
evaluation setup from the table above, so this is motivation for a matched comparison rather
|
| 204 |
-
than a controlled comparison with this recipe. Templated training needs no labeled documents,
|
| 205 |
-
but still uses compute.
|
| 206 |
-
|
| 207 |
-
For your task, compare with a simple baseline such as TF-IDF plus logistic regression using
|
| 208 |
-
the same training and evaluation rows. A zero-shot comparison can also be useful when class
|
| 209 |
-
names describe the task well. Use repeated seeds and appropriate task metrics before drawing
|
| 210 |
-
conclusions from small accuracy differences. This recipe trains and evaluates a supervised
|
| 211 |
-
classifier; built-in templated zero-shot training is a separate possible extension.
|
| 212 |
-
|
| 213 |
-
### Real-world data: a worked failure
|
| 214 |
-
|
| 215 |
-
`biglam/hansard_speech` (2.7M parliamentary speeches, predicting `party` from `speech`) is the
|
| 216 |
-
case where none of the convenient properties hold, and it is instructive precisely because it
|
| 217 |
-
produces no score:
|
| 218 |
-
|
| 219 |
-
- **No held-out split**, so the eval set has to be carved from train — the numbers stop being
|
| 220 |
-
comparable to anything published.
|
| 221 |
-
- **~9.5% of rows have a blank `party`**, which without the drop trains an `""` class.
|
| 222 |
-
- **28 parties after cleaning, nine of which cannot supply 8 examples** (`Respect` 4,
|
| 223 |
-
`Independent SDP` 2, `Change UK` 1). The requested eight-example budget cannot be met for those classes.
|
| 224 |
-
- **1,878 steps at ~11s/step on CPU** — the script refuses it, projecting well past an hour.
|
| 225 |
-
|
| 226 |
-
On completed runs, the model card discloses a carved evaluation split, per-class training counts
|
| 227 |
-
and classes below the requested sample count. Dropped-row counts and measured truncation are
|
| 228 |
-
reported in the logs; retain those logs alongside the model when documenting data preparation.
|
| 229 |
-
|
| 230 |
-
### Many classes: watch the pair count
|
| 231 |
-
|
| 232 |
-
SetFit trains on pairs drawn from every combination of training examples, so the pair count grows
|
| 233 |
-
with the **square** of the training-set size — which is `--num-samples` x number of classes. The
|
| 234 |
-
script logs the estimate before training starts:
|
| 235 |
-
|
| 236 |
-
| Dataset | Strategy | Pairs | Steps |
|
| 237 |
-
|---|---|---|---|
|
| 238 |
-
| ag_news (4 classes x 8) | `oversampling` (default) | 768 | 48 |
|
| 239 |
-
| banking77 (77 classes x 8) | `oversampling` (default) | 374,528 | 23,408 |
|
| 240 |
-
| banking77 (77 classes x 8) | `undersampling` | 4,312 | 270 |
|
| 241 |
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
|
|
|
|
|
|
| 246 |
|
| 247 |
-
|
| 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 |
|
|
@@ -296,357 +248,74 @@ 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`)
|
| 302 |
|
| 303 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
|
| 305 |
-
|
|
|
|
|
|
|
|
|
|
| 306 |
|
| 307 |
-
|
| 308 |
-
# Classify IMDB reviews
|
| 309 |
-
uv run classify-dataset.py \
|
| 310 |
-
--input-dataset stanfordnlp/imdb \
|
| 311 |
-
--column text \
|
| 312 |
-
--labels "positive,negative" \
|
| 313 |
-
--output-dataset user/imdb-classified
|
| 314 |
-
```
|
| 315 |
-
|
| 316 |
-
That's it! No installation, no setup - just `uv run`.
|
| 317 |
-
|
| 318 |
-
## 📋 Requirements
|
| 319 |
-
|
| 320 |
-
- **GPU Required**: Uses GPU-accelerated inference
|
| 321 |
-
- Python 3.10+
|
| 322 |
-
- UV (will handle all dependencies automatically)
|
| 323 |
-
- vLLM >= 0.6.6
|
| 324 |
-
|
| 325 |
-
## 🎯 Features
|
| 326 |
-
|
| 327 |
-
- **Guaranteed valid outputs** using structured generation with guided decoding
|
| 328 |
-
- **Zero-shot classification** without training data required
|
| 329 |
-
- **GPU-optimized** for maximum throughput and efficiency
|
| 330 |
-
- **Default model**: [HuggingFaceTB/SmolLM3-3B](https://huggingface.co/HuggingFaceTB/SmolLM3-3B) - a fast 3B model with native thinking capabilities (`<think>` tags)
|
| 331 |
-
- **Robust text handling** with preprocessing and validation
|
| 332 |
-
- **Automatic progress tracking** and detailed statistics
|
| 333 |
-
- **Direct Hub integration** - read and write datasets seamlessly
|
| 334 |
-
- **Label descriptions** support for providing context to improve accuracy
|
| 335 |
-
- **Reasoning mode** for interpretable classifications with thinking traces
|
| 336 |
-
- **JSON output parsing** for reliable extraction from reasoning mode
|
| 337 |
-
- **Optimized batching** with vLLM's automatic batch processing
|
| 338 |
-
- **Multiple guided backends** - supports outlines, xgrammar, and more
|
| 339 |
-
|
| 340 |
-
## 💻 Usage
|
| 341 |
-
|
| 342 |
-
### Basic Classification
|
| 343 |
-
|
| 344 |
-
```bash
|
| 345 |
-
uv run classify-dataset.py \
|
| 346 |
-
--input-dataset <dataset-id> \
|
| 347 |
-
--column <text-column> \
|
| 348 |
-
--labels <comma-separated-labels> \
|
| 349 |
-
--output-dataset <output-id>
|
| 350 |
-
```
|
| 351 |
-
|
| 352 |
-
### Arguments
|
| 353 |
-
|
| 354 |
-
**Required:**
|
| 355 |
-
|
| 356 |
-
- `--input-dataset`: Hugging Face dataset ID (e.g., `stanfordnlp/imdb`, `user/my-dataset`)
|
| 357 |
-
- `--column`: Name of the text column to classify
|
| 358 |
-
- `--labels`: Comma-separated classification labels (e.g., `"spam,ham"`)
|
| 359 |
-
- `--output-dataset`: Where to save the classified dataset
|
| 360 |
-
|
| 361 |
-
**Optional:**
|
| 362 |
-
|
| 363 |
-
- `--model`: Model to use (default: **`HuggingFaceTB/SmolLM3-3B`** - a fast 3B parameter model)
|
| 364 |
-
- `--label-descriptions`: Provide descriptions for each label to improve classification accuracy
|
| 365 |
-
- `--enable-reasoning`: Enable reasoning mode with thinking traces (adds reasoning column)
|
| 366 |
-
- `--split`: Dataset split to process (default: `train`)
|
| 367 |
-
- `--max-samples`: Limit samples for testing
|
| 368 |
-
- `--shuffle`: Shuffle dataset before selecting samples (useful for random sampling)
|
| 369 |
-
- `--shuffle-seed`: Random seed for shuffling (default: 42)
|
| 370 |
-
- `--temperature`: Generation temperature (default: 0.1)
|
| 371 |
-
- `--guided-backend`: Backend for guided decoding (default: `outlines`)
|
| 372 |
-
- `--hf-token`: Hugging Face token (or use `HF_TOKEN` env var)
|
| 373 |
-
|
| 374 |
-
### Label Descriptions
|
| 375 |
-
|
| 376 |
-
Provide context for your labels to improve classification accuracy:
|
| 377 |
-
|
| 378 |
-
```bash
|
| 379 |
-
uv run classify-dataset.py \
|
| 380 |
-
--input-dataset user/support-tickets \
|
| 381 |
-
--column content \
|
| 382 |
-
--labels "bug,feature,question,other" \
|
| 383 |
-
--label-descriptions "bug:something is broken,feature:request for new functionality,question:asking for help,other:anything else" \
|
| 384 |
-
--output-dataset user/tickets-classified
|
| 385 |
-
```
|
| 386 |
-
|
| 387 |
-
The model uses these descriptions to better understand what each label represents, leading to more accurate classifications.
|
| 388 |
-
|
| 389 |
-
### Reasoning Mode
|
| 390 |
-
|
| 391 |
-
Enable thinking traces for interpretable classifications:
|
| 392 |
-
|
| 393 |
-
```bash
|
| 394 |
-
uv run classify-dataset.py \
|
| 395 |
-
--input-dataset stanfordnlp/imdb \
|
| 396 |
-
--column text \
|
| 397 |
-
--labels "positive,negative,neutral" \
|
| 398 |
-
--enable-reasoning \
|
| 399 |
-
--output-dataset user/imdb-with-reasoning
|
| 400 |
-
```
|
| 401 |
-
|
| 402 |
-
When `--enable-reasoning` is used:
|
| 403 |
-
- The model generates step-by-step reasoning using SmolLM3's thinking capabilities
|
| 404 |
-
- Output includes three columns: `classification`, `reasoning`, and `parsing_success`
|
| 405 |
-
- Final answer must be in JSON format: `{"label": "chosen_label"}`
|
| 406 |
-
- Useful for understanding complex classification decisions
|
| 407 |
-
- Trade-off: Slower but more interpretable
|
| 408 |
-
|
| 409 |
-
## 📊 Examples
|
| 410 |
|
| 411 |
-
|
| 412 |
|
| 413 |
```bash
|
| 414 |
-
uv run
|
|
|
|
| 415 |
--input-dataset stanfordnlp/imdb \
|
| 416 |
--column text \
|
| 417 |
--labels "positive,negative" \
|
| 418 |
-
--output-dataset
|
|
|
|
| 419 |
```
|
| 420 |
|
| 421 |
-
|
|
|
|
|
|
|
|
|
|
| 422 |
|
| 423 |
```bash
|
| 424 |
-
|
| 425 |
-
hf jobs uv run \
|
| 426 |
-
--flavor l4x1 \
|
| 427 |
-
--image vllm/vllm-openai:latest \
|
| 428 |
https://huggingface.co/datasets/uv-scripts/classification/raw/main/classify-dataset.py \
|
| 429 |
--input-dataset user/support-tickets \
|
| 430 |
--column content \
|
| 431 |
--labels "bug,feature_request,question,other" \
|
| 432 |
--label-descriptions "bug:code or product not working as expected,feature_request:asking for new functionality,question:seeking help or clarification,other:general comments or feedback" \
|
| 433 |
-
--output-dataset user/tickets-classified
|
| 434 |
-
```
|
| 435 |
-
|
| 436 |
-
### News Categorization
|
| 437 |
-
|
| 438 |
-
```bash
|
| 439 |
-
# Using SmolLM3-3B for efficient news classification
|
| 440 |
-
hf jobs uv run \
|
| 441 |
-
--flavor l4x1 \
|
| 442 |
-
--image vllm/vllm-openai:latest \
|
| 443 |
-
https://huggingface.co/datasets/uv-scripts/classification/raw/main/classify-dataset.py \
|
| 444 |
-
--input-dataset ag_news \
|
| 445 |
-
--column text \
|
| 446 |
-
--labels "world,sports,business,tech" \
|
| 447 |
-
--output-dataset user/ag-news-categorized
|
| 448 |
-
```
|
| 449 |
-
|
| 450 |
-
### Complex Classification with Reasoning
|
| 451 |
-
|
| 452 |
-
```bash
|
| 453 |
-
# SmolLM3's thinking mode for nuanced feedback analysis
|
| 454 |
-
hf jobs uv run \
|
| 455 |
-
--flavor l4x1 \
|
| 456 |
-
--image vllm/vllm-openai:latest \
|
| 457 |
-
https://huggingface.co/datasets/uv-scripts/classification/raw/main/classify-dataset.py \
|
| 458 |
-
--input-dataset user/customer-feedback \
|
| 459 |
-
--column text \
|
| 460 |
-
--labels "very_positive,positive,neutral,negative,very_negative" \
|
| 461 |
-
--label-descriptions "very_positive:extremely satisfied,positive:generally satisfied,neutral:mixed feelings,negative:dissatisfied,very_negative:extremely dissatisfied" \
|
| 462 |
--enable-reasoning \
|
| 463 |
-
--output-dataset
|
| 464 |
-
```
|
| 465 |
-
|
| 466 |
-
This combines label descriptions with reasoning mode for maximum interpretability.
|
| 467 |
-
|
| 468 |
-
### ArXiv ML Research Classification
|
| 469 |
-
|
| 470 |
-
Classify academic papers into machine learning research areas:
|
| 471 |
-
|
| 472 |
-
```bash
|
| 473 |
-
# Fast classification with random sampling
|
| 474 |
-
uv run classify-dataset.py \
|
| 475 |
-
--input-dataset librarian-bots/arxiv-metadata-snapshot \
|
| 476 |
-
--column abstract \
|
| 477 |
-
--labels "llm,computer_vision,reinforcement_learning,optimization,theory,other" \
|
| 478 |
-
--label-descriptions "llm:language models and NLP,computer_vision:image and video processing,reinforcement_learning:RL and decision making,optimization:training and efficiency,theory:theoretical ML foundations,other:other ML topics" \
|
| 479 |
-
--output-dataset user/arxiv-ml-classified \
|
| 480 |
-
--split "train[:10000]" \
|
| 481 |
-
--max-samples 100 \
|
| 482 |
-
--shuffle
|
| 483 |
-
|
| 484 |
-
# With reasoning for nuanced classification
|
| 485 |
-
hf jobs uv run \
|
| 486 |
-
--flavor l4x1 \
|
| 487 |
-
--image vllm/vllm-openai:latest \
|
| 488 |
-
https://huggingface.co/datasets/uv-scripts/classification/raw/main/classify-dataset.py \
|
| 489 |
-
--input-dataset librarian-bots/arxiv-metadata-snapshot \
|
| 490 |
-
--column abstract \
|
| 491 |
-
--labels "multimodal,agents,reasoning,safety,efficiency" \
|
| 492 |
-
--label-descriptions "multimodal:vision-language and cross-modal models,agents:autonomous agents and tool use,reasoning:reasoning and planning systems,safety:alignment and safety research,efficiency:model optimization and deployment" \
|
| 493 |
-
--enable-reasoning \
|
| 494 |
-
--output-dataset user/arxiv-frontier-research \
|
| 495 |
-
--split "train[:1000]" \
|
| 496 |
-
--max-samples 50
|
| 497 |
-
```
|
| 498 |
-
|
| 499 |
-
The reasoning mode is particularly valuable for academic abstracts where papers often span multiple topics and require careful analysis to determine the primary focus.
|
| 500 |
-
|
| 501 |
-
## 🚀 Running on HF Jobs
|
| 502 |
-
|
| 503 |
-
Optimized for [Hugging Face Jobs](https://huggingface.co/docs/hub/spaces-gpu-jobs) (requires Pro subscription or Team/Enterprise organization):
|
| 504 |
-
```bash
|
| 505 |
-
# Run on L4 GPU with vLLM image
|
| 506 |
-
hf jobs uv run \
|
| 507 |
-
--flavor l4x1 \
|
| 508 |
-
--image vllm/vllm-openai:latest \
|
| 509 |
-
https://huggingface.co/datasets/uv-scripts/classification/raw/main/classify-dataset.py \
|
| 510 |
-
--input-dataset stanfordnlp/imdb \
|
| 511 |
-
--column text \
|
| 512 |
-
--labels "positive,negative" \
|
| 513 |
-
--output-dataset user/imdb-classified
|
| 514 |
-
```
|
| 515 |
-
|
| 516 |
-
### GPU Flavors
|
| 517 |
-
- `l4x1`: **Recommended starting point** - great for SmolLM3
|
| 518 |
-
- `a10g-large`: More memory for larger batches or 7B+ models
|
| 519 |
-
- `a100-large`: Maximum performance for demanding workloads
|
| 520 |
-
|
| 521 |
-
## 🔧 Advanced Usage
|
| 522 |
-
|
| 523 |
-
### Random Sampling
|
| 524 |
-
|
| 525 |
-
When working with ordered datasets, use `--shuffle` with `--max-samples` to get a representative sample:
|
| 526 |
-
|
| 527 |
-
```bash
|
| 528 |
-
# Get 50 random reviews instead of the first 50
|
| 529 |
-
uv run classify-dataset.py \
|
| 530 |
-
--input-dataset stanfordnlp/imdb \
|
| 531 |
-
--column text \
|
| 532 |
-
--labels "positive,negative" \
|
| 533 |
-
--output-dataset user/imdb-sample \
|
| 534 |
-
--max-samples 50 \
|
| 535 |
-
--shuffle \
|
| 536 |
-
--shuffle-seed 123 # For reproducibility
|
| 537 |
-
```
|
| 538 |
-
|
| 539 |
-
This is especially important for:
|
| 540 |
-
- Chronologically ordered datasets (news, papers, social media)
|
| 541 |
-
- Pre-sorted datasets (by rating, category, etc.)
|
| 542 |
-
- Testing on diverse samples before processing the full dataset
|
| 543 |
-
|
| 544 |
-
### Using Different Models
|
| 545 |
-
|
| 546 |
-
By default, this script uses **[HuggingFaceTB/SmolLM3-3B](https://huggingface.co/HuggingFaceTB/SmolLM3-3B)** - a state-of-the-art 3B parameter model specifically designed for efficient inference. SmolLM3 features:
|
| 547 |
-
- Native thinking capabilities with `<think>` tags for step-by-step reasoning
|
| 548 |
-
- Excellent performance on classification tasks
|
| 549 |
-
- Fast inference speed (50-100 texts/second on A10)
|
| 550 |
-
- Low memory footprint allowing larger batch sizes
|
| 551 |
-
|
| 552 |
-
While you can use other models, SmolLM3 is recommended for its balance of quality, speed, and reasoning capabilities:
|
| 553 |
-
|
| 554 |
-
```bash
|
| 555 |
-
# Larger model for complex classification
|
| 556 |
-
uv run classify-dataset.py \
|
| 557 |
-
--input-dataset user/legal-docs \
|
| 558 |
-
--column text \
|
| 559 |
-
--labels "contract,patent,brief,memo,other" \
|
| 560 |
-
--output-dataset user/legal-classified \
|
| 561 |
-
--model Qwen/Qwen2.5-7B-Instruct
|
| 562 |
```
|
| 563 |
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
```bash
|
| 569 |
-
uv run classify-dataset.py \
|
| 570 |
-
--input-dataset user/huge-dataset \
|
| 571 |
-
--column text \
|
| 572 |
-
--labels "A,B,C" \
|
| 573 |
-
--output-dataset user/huge-classified
|
| 574 |
-
```
|
| 575 |
-
|
| 576 |
-
## 📈 Performance
|
| 577 |
-
|
| 578 |
-
- **SmolLM3-3B (default)**: ~50-100 texts/second on A10
|
| 579 |
-
- **7B models**: ~20-50 texts/second on A10
|
| 580 |
-
- vLLM automatically optimizes batching for best throughput
|
| 581 |
-
- Performance scales with GPU memory and compute capability
|
| 582 |
-
|
| 583 |
-
## 🤝 How It Works
|
| 584 |
-
|
| 585 |
-
1. **vLLM**: Provides efficient GPU batch inference with automatic batching
|
| 586 |
-
2. **Guided Decoding**: Uses outlines backend to guarantee valid label outputs
|
| 587 |
-
3. **Structured Generation**: Constrains model outputs to exact label choices
|
| 588 |
-
4. **UV**: Handles all dependencies automatically
|
| 589 |
|
| 590 |
-
|
| 591 |
|
| 592 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 593 |
|
| 594 |
-
|
| 595 |
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
- A machine with NVIDIA GPU
|
| 599 |
-
- HF Jobs (recommended)
|
| 600 |
-
- Cloud GPU instances
|
| 601 |
-
|
| 602 |
-
### Out of Memory
|
| 603 |
-
|
| 604 |
-
- Use a smaller model
|
| 605 |
-
- Use a larger GPU (e.g., a100-large)
|
| 606 |
-
|
| 607 |
-
### Invalid/Skipped Texts
|
| 608 |
-
|
| 609 |
-
- Texts shorter than 3 characters are skipped
|
| 610 |
-
- Empty or None values are marked as invalid
|
| 611 |
-
- Very long texts are truncated to 4000 characters
|
| 612 |
-
|
| 613 |
-
### Classification Quality
|
| 614 |
-
|
| 615 |
-
- With guided decoding, outputs are guaranteed to be valid labels
|
| 616 |
-
- For better results, use clear and distinct label names
|
| 617 |
-
- Try the `reasoning` prompt style for complex classifications
|
| 618 |
-
- Use a larger model for nuanced tasks
|
| 619 |
-
|
| 620 |
-
### vLLM Version Issues
|
| 621 |
-
|
| 622 |
-
If you see `ImportError: cannot import name 'GuidedDecodingParams'`:
|
| 623 |
-
|
| 624 |
-
- Your vLLM version is too old (requires >= 0.6.6)
|
| 625 |
-
- The script specifies the correct version in its dependencies
|
| 626 |
-
- UV should automatically install the correct version
|
| 627 |
-
|
| 628 |
-
## 🔬 Advanced Workflows
|
| 629 |
-
|
| 630 |
-
For complex real-world workflows that integrate UV scripts with the Python HF Jobs API, see the [ArXiv ML Trends example](examples/arxiv-workflow/). This demonstrates:
|
| 631 |
-
|
| 632 |
-
- **Multi-stage pipelines**: Data preparation → GPU classification → Analysis
|
| 633 |
-
- **Python API orchestration**: Using `run_uv_job()` to manage GPU jobs programmatically
|
| 634 |
-
- **Production patterns**: Error handling, parallel execution, and incremental updates
|
| 635 |
-
- **Cost optimization**: Choosing appropriate compute resources for each task
|
| 636 |
-
|
| 637 |
-
```python
|
| 638 |
-
# Example: Submit a classification job via Python API
|
| 639 |
-
from huggingface_hub import run_uv_job
|
| 640 |
-
|
| 641 |
-
job = run_uv_job(
|
| 642 |
-
script="https://huggingface.co/datasets/uv-scripts/classification/raw/main/classify-dataset.py",
|
| 643 |
-
args=["--input-dataset", "my/dataset", "--labels", "A,B,C"],
|
| 644 |
-
flavor="l4x1",
|
| 645 |
-
image="vllm/vllm-openai:latest"
|
| 646 |
-
)
|
| 647 |
-
result = job.wait()
|
| 648 |
-
```
|
| 649 |
-
|
| 650 |
-
## 📝 License
|
| 651 |
|
| 652 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
viewer: false
|
| 3 |
+
tags: [uv-script, classification, fine-tuning, few-shot, zero-shot, decision-model, setfit, gliner2, vllm, structured-outputs, hf-jobs]
|
| 4 |
---
|
| 5 |
|
| 6 |
# Classification Scripts
|
| 7 |
|
| 8 |
+
Text classification on [HF Jobs](https://huggingface.co/docs/hub/jobs): label a dataset with a model that needs no training, or train your own classifier from labelled examples.
|
| 9 |
+
|
| 10 |
+
If you have seen [Jev](https://docs.typesafe.ai/introduction) and other "System One" models: the
|
| 11 |
+
models these scripts train are small, open versions of the same idea. They read a piece of data and
|
| 12 |
+
return a label with a probability, and you can train one on your own labels. For example, this
|
| 13 |
+
[demo](https://huggingface.co/spaces/davanstrien/hub-task-tagger) suggests task tags for any Hub
|
| 14 |
+
dataset; its model was fine-tuned with `train-gliner2.py` in 17 minutes.
|
| 15 |
+
|
| 16 |
+
To try it on your own account, this command fine-tunes a classifier for British Library book titles
|
| 17 |
+
(Fiction / Non-fiction). Training takes about 2 minutes on a `t4-small` and costs about $0.02.
|
| 18 |
+
Accuracy goes from 0.767 zero-shot to 0.907 fine-tuned. You get a private model repo, and its card
|
| 19 |
+
shows both scores next to the majority-class baseline. Copy and paste it as it is: the model goes
|
| 20 |
+
to your own account.
|
| 21 |
+
|
| 22 |
+
```bash
|
| 23 |
+
hf jobs uv run --flavor t4-small --timeout 1h --secrets HF_TOKEN \
|
| 24 |
+
https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-gliner2.py \
|
| 25 |
+
biglam/blbooksgenre gliner2-blbooks-genre \
|
| 26 |
+
--dataset-config title_genre_classifiction --text-column title
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
You need the `hf` CLI, signed in, and Jobs credit: see the [Jobs quickstart](https://huggingface.co/docs/hub/jobs-quickstart).
|
| 30 |
|
| 31 |
| Script | What it does |
|
| 32 |
|--------|--------------|
|
| 33 |
| [`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 |
|
| 34 |
+
| [`train-gliner2.py`](#zero-shot-first-then-fine-tune-gliner2) | **Fine-tune** [GLiNER2](https://huggingface.co/fastino), a small model (74M–287M) that already classifies zero-shot, and report the zero-shot score next to the fine-tuned one |
|
| 35 |
+
| [`train-setfit.py`](#few-shot-with-setfit-train-setfitpy) | **Few-shot** train a classifier from 8-64 labels per class with [SetFit](https://huggingface.co/docs/setfit) — runs on CPU or GPU |
|
| 36 |
| [`train-classifier.py`](#fine-tune-a-classifier-train-classifierpy) | **Fine-tune** an encoder into a classifier (default: [LFM2.5-Encoder-350M](https://huggingface.co/LiquidAI/LFM2.5-Encoder-350M)) and push it to the Hub |
|
| 37 |
| [`classify-dataset.py`](#zero-shot-classification-classify-datasetpy) | **Zero-shot** classify a dataset with an instruction LLM (SmolLM3 + vLLM, structured outputs) |
|
| 38 |
+
| [`classify-dataset-sglang.py`](#zero-shot-classification-classify-datasetpy) | Zero-shot variant on SGLang (reasoning-aware `<think>` models) |
|
| 39 |
|
| 40 |
Pick by how many labels you have:
|
| 41 |
|
|
|
|
| 46 |
| a few hundred to a few thousand | `train-gliner2.py`, which also shows you what zero-shot already gets | small GPU (`t4-small`) |
|
| 47 |
| a few thousand or more | `train-classifier.py` | GPU |
|
| 48 |
|
| 49 |
+
The rungs chain: bootstrap labels with `classify-gliner2.py` or `classify-dataset.py`, review them,
|
| 50 |
+
then train a small dedicated model on what you kept. Each rung is one command, so you can move up
|
| 51 |
+
as you collect more labels.
|
| 52 |
|
| 53 |
## Zero-shot first, then fine-tune (GLiNER2)
|
| 54 |
|
|
|
|
| 56 |
small model on your labels, in minutes and for a few cents on one GPU. The result is a model
|
| 57 |
that returns a label and a probability for every row, and is small enough to run on a CPU.
|
| 58 |
|
| 59 |
+
[GLiNER2](https://github.com/fastino-ai/GLiNER2) ([models from Fastino](https://huggingface.co/fastino)) is a small encoder that reads the label names
|
| 60 |
as part of its input, so it classifies with no training at all, and fine-tuning teaches it what
|
| 61 |
your labels mean in your data. (For entity extraction with the original GLiNER library, see
|
| 62 |
[`uv-scripts/gliner`](https://huggingface.co/datasets/uv-scripts/gliner).) Two scripts:
|
| 63 |
|
| 64 |
- **`train-gliner2.py`** scores the base model zero-shot, fine-tunes it on your labels, and
|
| 65 |
+
scores it again on the same held-out rows. The model card reports both scores next to the
|
| 66 |
+
majority-class baseline.
|
| 67 |
- **`classify-gliner2.py`** labels a whole dataset. Pass `--labels` for zero-shot, or `--model`
|
| 68 |
with a `train-gliner2.py` output; the tasks and labels are read from the model repo.
|
| 69 |
Labels are passed as separate words; quote a label with spaces:
|
| 70 |
`--labels World Sports Business "Science and technology"`. A fine-tuned model is passed
|
| 71 |
+
by name: `--model gliner2-blbooks-genre`. A name on its own means your account; use `org/name`
|
| 72 |
+
for an organisation.
|
| 73 |
|
| 74 |
### Quick start
|
| 75 |
|
|
|
|
| 77 |
# fine-tune: British Library book titles -> Fiction / Non-fiction
|
| 78 |
hf jobs uv run --flavor t4-small --timeout 1h --secrets HF_TOKEN \
|
| 79 |
https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-gliner2.py \
|
| 80 |
+
biglam/blbooksgenre gliner2-blbooks-genre \
|
| 81 |
--dataset-config title_genre_classifiction --text-column title
|
| 82 |
|
| 83 |
# label a dataset with that model
|
| 84 |
hf jobs uv run --flavor t4-small --timeout 1h --secrets HF_TOKEN \
|
| 85 |
https://huggingface.co/datasets/uv-scripts/classification/raw/main/classify-gliner2.py \
|
| 86 |
+
biglam/blbooksgenre blbooks-genre-predictions \
|
| 87 |
+
--dataset-config title_genre_classifiction --text-column title --model gliner2-blbooks-genre
|
| 88 |
|
| 89 |
# or skip training: zero-shot from label names
|
| 90 |
hf jobs uv run --flavor t4-small --timeout 1h --secrets HF_TOKEN \
|
| 91 |
https://huggingface.co/datasets/uv-scripts/classification/raw/main/classify-gliner2.py \
|
| 92 |
+
fancyzhx/ag_news ag-news-topics --split test \
|
| 93 |
--labels World Sports Business "Science and technology" --task-name topic
|
| 94 |
```
|
| 95 |
|
|
|
|
| 99 |
|
| 100 |
These commands use the default base model, `fastino/gliner2.5-multi-v1` (multilingual). For
|
| 101 |
English text, `--base-model fastino/gliner2.5-base-v1` is smaller and faster;
|
| 102 |
+
`gliner2.5-small-v1` is the fastest and loses about 4 points on the 52-tag example. Sizes and speeds: [Choosing a model size](GLINER2-NOTES.md#choosing-a-model-size).
|
| 103 |
+
|
| 104 |
+
### Results
|
| 105 |
|
| 106 |
+
Fine-tuning beat zero-shot on every dataset below. The public-dataset runs took 2 to 30 minutes of
|
| 107 |
+
training on one GPU and cost $0.01 to $0.20; the 52-tag example took 17 minutes and about $1.50.
|
| 108 |
|
| 109 |
| Dataset | Task | Labels | Train rows × epochs | Train time | Train cost | Metric | Majority floor | Zero-shot | Fine-tuned |
|
| 110 |
|---|---|---|---|---|---|---|---|---|---|
|
|
|
|
| 119 |
Most rows are single, deliberately small runs that test the script, not tuned results. Seed ranges,
|
| 120 |
out-of-memory history and GPU comparisons are in [GLINER2-NOTES.md](GLINER2-NOTES.md).
|
| 121 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
### Larger or fixed label sets
|
| 123 |
|
| 124 |
For tens of labels scored together (a taxonomy, a fixed tag list), or data in a bucket, see
|
|
|
|
| 130 |
A GLiNER2.5-base model fine-tuned with this script on 16,000 Hub datasets suggests task tags for
|
| 131 |
a dataset from its column names and first row, among the 52 tags the Hub offers. Its first
|
| 132 |
suggestion matches one of the owner's tags 69% of the time on 3,000 newer datasets from owners it
|
| 133 |
+
never saw. Owners' tags are a noisy target: in a hand-checked sample, about 1 in 10 datasets was
|
| 134 |
+
missing a tag that fits.
|
| 135 |
+
|
| 136 |
+
[Try the demo](https://huggingface.co/spaces/davanstrien/hub-task-tagger): paste a dataset id and
|
| 137 |
+
see the suggested tags, the owner's tags and the exact text the model read. On a free 2-vCPU Space
|
| 138 |
+
one prediction takes about 0.7–1 s.
|
| 139 |
+
[Model](https://huggingface.co/davanstrien/hub-task-tagger-gliner2.5-base) · [Notes on how it was trained](GLINER2-NOTES.md#a-larger-label-set-52-hub-task-tags)
|
| 140 |
|
| 141 |
### Good to know
|
| 142 |
|
|
|
|
| 151 |
|
| 152 |
An alternative when you have only a handful of labelled examples per class (8-64) and want a sentence-transformer model.
|
| 153 |
|
| 154 |
+
Trains a [SetFit](https://huggingface.co/docs/setfit) classifier from a handful of labelled
|
| 155 |
examples per class. SetFit finetunes a sentence-transformer body on contrastive pairs, then fits a
|
| 156 |
logistic regression head on the resulting embeddings.
|
| 157 |
|
|
|
|
| 159 |
training, particularly with larger models, longer texts or more classes. The same model and
|
| 160 |
training settings work on either; the recipe uses the available accelerator automatically.
|
| 161 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
```bash
|
| 163 |
# 8 labels per class, on CPU
|
| 164 |
hf jobs uv run --flavor cpu-basic --timeout 20m --secrets HF_TOKEN \
|
|
|
|
| 171 |
fancyzhx/ag_news username/ag-news-setfit-gpu --num-samples 8
|
| 172 |
```
|
| 173 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
### Measured
|
| 175 |
|
| 176 |
8 labels per class, seed 42, evaluated on each dataset's own held-out split (capped at 500
|
|
|
|
| 188 |
standard deviation across ten seeds for exactly this reason. Run your own task before trusting
|
| 189 |
any of these numbers.
|
| 190 |
|
| 191 |
+
### Good to know
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
|
| 193 |
+
- **Default body**: [`all-MiniLM-L6-v2`](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) (22M), chosen for CPU speed. Swap it with `--body-model`; set `--max-seq-length` within its context window and add any task prefix it needs yourself. See [Choosing another body or longer context](SETFIT-NOTES.md#choosing-another-body-or-longer-context).
|
| 194 |
+
- **Single-label only.** A multi-label column exits with a pointer to `train-classifier.py`.
|
| 195 |
+
- **Beat more than the majority baseline.** Every run reports it, but `emotion` beat it by under 2 points; compare with TF-IDF plus logistic regression or zero-shot on the same rows. See [Compare more than the majority baseline](SETFIT-NOTES.md#compare-more-than-the-majority-baseline).
|
| 196 |
+
- **Many classes: watch the pair count.** Pairs grow with the square of the training-set size; at 77 classes use `--sampling-strategy undersampling`. See [Many classes](SETFIT-NOTES.md#many-classes-watch-the-pair-count).
|
| 197 |
+
- **It refuses runs projected above `--max-minutes`** (default 60). On `biglam/hansard_speech` (2.7M speeches, 28 parties) it refused to train and produced no score, and [the worked failure](SETFIT-NOTES.md#real-world-data-a-worked-failure) shows why.
|
| 198 |
+
- **Load it with `SetFitModel.from_pretrained(repo)`**, not `AutoModelForSequenceClassification`: a SetFit model is a sentence-transformer body plus a scikit-learn head.
|
| 199 |
|
| 200 |
+
Evaluation split, metrics, dropped rows and `--private`: [SETFIT-NOTES.md](SETFIT-NOTES.md#behaviour-details).
|
|
|
|
| 201 |
|
| 202 |
## Fine-tune a classifier (`train-classifier.py`)
|
| 203 |
|
| 204 |
Fine-tunes a text-classification encoder on any Hub dataset and pushes the trained model
|
| 205 |
back to the Hub — download, train, evaluate, push, and reload-verify in one job.
|
| 206 |
|
| 207 |
+
- **Default model**: [LiquidAI/LFM2.5-Encoder-350M](https://huggingface.co/LiquidAI/LFM2.5-Encoder-350M) — a bidirectional encoder that LiquidAI reports beats ModernBERT-base on GLUE/SuperGLUE, and handles 8,192-token documents. Any Hub encoder works via `--model` (ModernBERT, BERT, DeBERTa, …).
|
| 208 |
- **Single-label and multi-label**, auto-detected from the label column (`ClassLabel`/string/int → cross-entropy; list of labels → BCE + per-label threshold tuning).
|
| 209 |
- **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.
|
| 210 |
|
|
|
|
| 248 |
[`uv-scripts/vllm`](https://huggingface.co/datasets/uv-scripts/vllm)'s
|
| 249 |
`classify-dataset.py` for large-scale batch inference with the model you just trained.
|
| 250 |
|
| 251 |
+
## Zero-shot classification (`classify-dataset.py`)
|
|
|
|
|
|
|
| 252 |
|
| 253 |
+
Label a dataset with an instruction LLM and no training data. You give a list of labels; the
|
| 254 |
+
model picks one per row, and guided decoding (structured outputs) makes sure every answer is one
|
| 255 |
+
of your labels. The default model is
|
| 256 |
+
[HuggingFaceTB/SmolLM3-3B](https://huggingface.co/HuggingFaceTB/SmolLM3-3B); any instruction
|
| 257 |
+
model works via `--model`. The result is your dataset with a new `classification` column.
|
| 258 |
|
| 259 |
+
Two scripts do this. `classify-dataset.py` runs on vLLM and is the one to start with.
|
| 260 |
+
`classify-dataset-sglang.py` runs the same task on SGLang, for reasoning models that write
|
| 261 |
+
`<think>` traces; its options differ (`--reasoning`, `--save-reasoning`, `--batch-size`,
|
| 262 |
+
`--grammar-backend`), so check its `--help`.
|
| 263 |
|
| 264 |
+
### Quick start
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
|
| 266 |
+
A GPU is required. Run on Jobs with the vLLM image:
|
| 267 |
|
| 268 |
```bash
|
| 269 |
+
hf jobs uv run --flavor l4x1 --image vllm/vllm-openai:latest --secrets HF_TOKEN \
|
| 270 |
+
https://huggingface.co/datasets/uv-scripts/classification/raw/main/classify-dataset.py \
|
| 271 |
--input-dataset stanfordnlp/imdb \
|
| 272 |
--column text \
|
| 273 |
--labels "positive,negative" \
|
| 274 |
+
--output-dataset username/imdb-classified \
|
| 275 |
+
--max-samples 100 --shuffle
|
| 276 |
```
|
| 277 |
|
| 278 |
+
`--max-samples` with `--shuffle` takes a random sample, which matters for datasets sorted by
|
| 279 |
+
date or label. Drop both to label the whole split.
|
| 280 |
+
|
| 281 |
+
### With reasoning and label descriptions
|
| 282 |
|
| 283 |
```bash
|
| 284 |
+
hf jobs uv run --flavor l4x1 --image vllm/vllm-openai:latest --secrets HF_TOKEN \
|
|
|
|
|
|
|
|
|
|
| 285 |
https://huggingface.co/datasets/uv-scripts/classification/raw/main/classify-dataset.py \
|
| 286 |
--input-dataset user/support-tickets \
|
| 287 |
--column content \
|
| 288 |
--labels "bug,feature_request,question,other" \
|
| 289 |
--label-descriptions "bug:code or product not working as expected,feature_request:asking for new functionality,question:seeking help or clarification,other:general comments or feedback" \
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
--enable-reasoning \
|
| 291 |
+
--output-dataset username/tickets-classified
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
```
|
| 293 |
|
| 294 |
+
With `--enable-reasoning` the model thinks step by step before it answers, and the output also
|
| 295 |
+
has `reasoning` and `parsing_success` columns. Reasoning mode turns off structured outputs: the
|
| 296 |
+
model must end with `{"label": "..."}`, and rows where that cannot be parsed are marked in
|
| 297 |
+
`parsing_success`. It is slower, but you can read why each label was chosen.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
|
| 299 |
+
### Options
|
| 300 |
|
| 301 |
+
| Option | What it does |
|
| 302 |
+
|---|---|
|
| 303 |
+
| `--model` | Model to use (default `HuggingFaceTB/SmolLM3-3B`) |
|
| 304 |
+
| `--label-descriptions` | `label:description,...` pairs that tell the model what each label means |
|
| 305 |
+
| `--enable-reasoning` | Think before answering; adds `reasoning` and `parsing_success` columns |
|
| 306 |
+
| `--split` | Split to process (default `train`) |
|
| 307 |
+
| `--max-samples` | Label only the first N rows (or N random rows with `--shuffle`) |
|
| 308 |
+
| `--shuffle`, `--shuffle-seed` | Shuffle before `--max-samples` (seed default 42) |
|
| 309 |
|
| 310 |
+
Run `uv run classify-dataset.py --help` for all options.
|
| 311 |
|
| 312 |
+
### Good to know
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
|
| 314 |
+
- **Speed**: about 50-100 texts/second for SmolLM3-3B on an A10, and 20-50 for 7B models.
|
| 315 |
+
`l4x1` is a good start; use `a10g-large` or larger for 7B+ models or out-of-memory errors.
|
| 316 |
+
- **Text handling**: texts shorter than 3 characters and empty values are skipped; texts are
|
| 317 |
+
truncated to 4,000 characters.
|
| 318 |
+
- **Label names matter.** Use clear, distinct names, add `--label-descriptions` when names are
|
| 319 |
+
ambiguous, and try a larger model for nuanced tasks.
|
| 320 |
+
- **vLLM version**: `ImportError: cannot import name GuidedDecodingParams` means the vLLM
|
| 321 |
+
version does not match; the script requires `vllm>=0.6.6`.
|
SETFIT-NOTES.md
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SetFit script: findings and behaviour details
|
| 2 |
+
|
| 3 |
+
Notes behind `train-setfit.py`. The README has what you need to run it; this file records the
|
| 4 |
+
longer findings and the full behaviour details.
|
| 5 |
+
|
| 6 |
+
## Compare more than the majority baseline
|
| 7 |
+
|
| 8 |
+
The `emotion` run reached **0.370** accuracy against a **0.352** majority baseline. Other
|
| 9 |
+
single-seed body-model runs reached 0.418 (`bge-small`) and 0.410 (`paraphrase-mpnet-base-v2`).
|
| 10 |
+
These results call for further evaluation; they do not establish a limit on the task or method.
|
| 11 |
+
|
| 12 |
+
SetFit's [zero-shot guide](https://huggingface.co/docs/setfit/how_to/zero_shot) reports **0.591**
|
| 13 |
+
on emotion using BGE and training examples templated from the class names. It uses a different
|
| 14 |
+
evaluation setup from the table above, so this is motivation for a matched comparison rather
|
| 15 |
+
than a controlled comparison with this recipe. Templated training needs no labeled documents,
|
| 16 |
+
but still uses compute.
|
| 17 |
+
|
| 18 |
+
For your task, compare with a simple baseline such as TF-IDF plus logistic regression using
|
| 19 |
+
the same training and evaluation rows. A zero-shot comparison can also be useful when class
|
| 20 |
+
names describe the task well. Use repeated seeds and appropriate task metrics before drawing
|
| 21 |
+
conclusions from small accuracy differences. This recipe trains and evaluates a supervised
|
| 22 |
+
classifier; built-in templated zero-shot training is a separate possible extension.
|
| 23 |
+
|
| 24 |
+
## Real-world data: a worked failure
|
| 25 |
+
|
| 26 |
+
`biglam/hansard_speech` (2.7M parliamentary speeches, predicting `party` from `speech`) is the
|
| 27 |
+
case where none of the convenient properties hold, and it is instructive precisely because it
|
| 28 |
+
produces no score:
|
| 29 |
+
|
| 30 |
+
- **No held-out split**, so the eval set has to be carved from train — the numbers stop being
|
| 31 |
+
comparable to anything published.
|
| 32 |
+
- **~9.5% of rows have a blank `party`**, which without the drop trains an `""` class.
|
| 33 |
+
- **28 parties after cleaning, nine of which cannot supply 8 examples** (`Respect` 4,
|
| 34 |
+
`Independent SDP` 2, `Change UK` 1). The requested eight-example budget cannot be met for those classes.
|
| 35 |
+
- **1,878 steps at ~11s/step on CPU** — the script refuses it, projecting well past an hour.
|
| 36 |
+
|
| 37 |
+
On completed runs, the model card discloses a carved evaluation split, per-class training counts
|
| 38 |
+
and classes below the requested sample count. Dropped-row counts and measured truncation are
|
| 39 |
+
reported in the logs; retain those logs alongside the model when documenting data preparation.
|
| 40 |
+
|
| 41 |
+
## Many classes: watch the pair count
|
| 42 |
+
|
| 43 |
+
SetFit trains on pairs drawn from every combination of training examples, so the pair count grows
|
| 44 |
+
with the **square** of the training-set size — which is `--num-samples` x number of classes. The
|
| 45 |
+
script logs the estimate before training starts:
|
| 46 |
+
|
| 47 |
+
| Dataset | Strategy | Pairs | Steps |
|
| 48 |
+
|---|---|---|---|
|
| 49 |
+
| ag_news (4 classes x 8) | `oversampling` (default) | 768 | 48 |
|
| 50 |
+
| banking77 (77 classes x 8) | `oversampling` (default) | 374,528 | 23,408 |
|
| 51 |
+
| banking77 (77 classes x 8) | `undersampling` | 4,312 | 270 |
|
| 52 |
+
|
| 53 |
+
At 77 classes the default would take roughly 15 hours on `cpu-basic`; `--sampling-strategy
|
| 54 |
+
undersampling` finished in 18 seconds on a T4 in the recorded run. The script reports the pair
|
| 55 |
+
and step counts, then measures step time to check `--max-minutes`. When it refuses training,
|
| 56 |
+
it suggests undersampling where applicable and estimates whether that would fit the budget.
|
| 57 |
+
|
| 58 |
+
## Choosing another body or longer context
|
| 59 |
+
|
| 60 |
+
`--body-model` accepts a Sentence Transformer checkpoint. Set `--max-seq-length` within that
|
| 61 |
+
model's supported context window; increasing it cannot extend a model's native limit or restore
|
| 62 |
+
text already shortened during dataset preparation. Longer sequences can need a smaller
|
| 63 |
+
`--batch-size` or more GPU memory. The recipe measures training cost on the selected hardware.
|
| 64 |
+
|
| 65 |
+
Follow the body's task-prefix instructions when preparing inputs. For example,
|
| 66 |
+
[`nomic-ai/modernbert-embed-base`](https://huggingface.co/nomic-ai/modernbert-embed-base)
|
| 67 |
+
uses Nomic's task prefixes: classification inputs should begin with `classification: `.
|
| 68 |
+
Include the same prefix during training, evaluation and inference. The recipe does not add it
|
| 69 |
+
automatically. Retain the original texts and the preprocessing details with the model.
|
| 70 |
+
|
| 71 |
+
## Behaviour details
|
| 72 |
+
|
| 73 |
+
- **Evaluation split** follows the same precedence as `train-classifier.py`: `--eval-split` if given, else `validation`, else `test`, else a stratified carve-out of `--eval-fraction` from train.
|
| 74 |
+
- **Metrics match `train-classifier.py`** (accuracy + macro F1). Match evaluation rows and preprocessing when comparing runs.
|
| 75 |
+
- **`--num-samples`** sets labelled examples per class (default 8). **`--sampling-strategy`** controls contrastive pairing: `oversampling` (default), `undersampling`, `unique`.
|
| 76 |
+
- **Every run reports a majority baseline.** The run warns when accuracy fails to beat it, or the gain is below five percentage points. That fixed threshold is a review heuristic, not a measured noise level or significance test.
|
| 77 |
+
- **It estimates training time before starting.** The script times forward/backward passes on actual texts and hardware, then refuses training projected above `--max-minutes` (default 60). Setup, evaluation and upload take additional time. A measurement error can skip this guard; use Jobs `--timeout` to enforce a wall-clock limit.
|
| 78 |
+
- **Rows with missing or blank labels or texts are dropped**, with a count. Missing labels include `ClassLabel`'s `-1` sentinel and numeric NaN; plain integer `-1` remains a valid class. Splits with no usable labelled text, fewer than two observed training classes, and missing or non-string text columns exit before model loading.
|
| 79 |
+
- **`--private` verifies the output repository is private before training.** If the destination already exists publicly, choose a new repo or change its visibility first.
|
classify-gliner2.py
CHANGED
|
@@ -323,6 +323,13 @@ Classified {total} rows in {round(seconds)} seconds ({total / max(seconds, 1e-9)
|
|
| 323 |
"""
|
| 324 |
|
| 325 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 326 |
def main(args) -> None:
|
| 327 |
token = args.hf_token or os.environ.get("HF_TOKEN")
|
| 328 |
if not token:
|
|
@@ -331,6 +338,9 @@ def main(args) -> None:
|
|
| 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(
|
|
@@ -437,7 +447,7 @@ def main(args) -> None:
|
|
| 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 (
|
| 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)")
|
|
|
|
| 323 |
"""
|
| 324 |
|
| 325 |
|
| 326 |
+
def in_own_account(api: HfApi, repo_id: str) -> str:
|
| 327 |
+
"""A bare name ("my-model") means a repo in your own account: return "<username>/my-model"."""
|
| 328 |
+
if "/" in repo_id:
|
| 329 |
+
return repo_id
|
| 330 |
+
return f"{api.whoami()['name']}/{repo_id}"
|
| 331 |
+
|
| 332 |
+
|
| 333 |
def main(args) -> None:
|
| 334 |
token = args.hf_token or os.environ.get("HF_TOKEN")
|
| 335 |
if not token:
|
|
|
|
| 338 |
|
| 339 |
# push_to_hub(private=True) leaves an existing repo's visibility alone, so check before the work.
|
| 340 |
api = HfApi(token=token)
|
| 341 |
+
args.output_dataset = in_own_account(api, args.output_dataset)
|
| 342 |
+
if not os.path.exists(args.model):
|
| 343 |
+
args.model = in_own_account(api, args.model)
|
| 344 |
output_exists = api.repo_exists(args.output_dataset, repo_type="dataset")
|
| 345 |
if not args.public and output_exists and not api.repo_info(args.output_dataset, repo_type="dataset").private:
|
| 346 |
sys.exit(
|
|
|
|
| 447 |
def parse_args():
|
| 448 |
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 449 |
parser.add_argument("input_dataset", help="Input dataset ID")
|
| 450 |
+
parser.add_argument("output_dataset", help="Output dataset: a name for your own account (my-dataset) or a full ID (org/my-dataset)")
|
| 451 |
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})")
|
| 452 |
parser.add_argument("--labels", nargs="+", help="Label names for zero-shot classification. Overrides the tasks recorded in the model repo.")
|
| 453 |
parser.add_argument("--task-name", default="label", help="Name of the --labels task; sets the output column names (default: label)")
|
train-gliner2.py
CHANGED
|
@@ -20,8 +20,8 @@ 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
|
| 24 |
-
|
| 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):
|
|
@@ -1009,6 +1009,13 @@ Produced by [`train-gliner2.py`]({SCRIPT_URL}) from
|
|
| 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 |
|
|
@@ -1047,6 +1054,7 @@ def main(args) -> None:
|
|
| 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)
|
|
@@ -1178,7 +1186,7 @@ def parse_args():
|
|
| 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 (
|
| 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",
|
|
|
|
| 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.
|
| 24 |
+
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):
|
|
|
|
| 1009 |
"""
|
| 1010 |
|
| 1011 |
|
| 1012 |
+
def in_own_account(api: HfApi, repo_id: str) -> str:
|
| 1013 |
+
"""A bare name ("my-model") means a repo in your own account: return "<username>/my-model"."""
|
| 1014 |
+
if "/" in repo_id:
|
| 1015 |
+
return repo_id
|
| 1016 |
+
return f"{api.whoami()['name']}/{repo_id}"
|
| 1017 |
+
|
| 1018 |
+
|
| 1019 |
def ensure_output_repo(api: HfApi, repo_id: str, private: bool) -> None:
|
| 1020 |
"""Create the model repo, and refuse to train if a private run would push to a public repo.
|
| 1021 |
|
|
|
|
| 1054 |
if args.no_push:
|
| 1055 |
logger.info("--no-push: the model will stay in %s.", os.path.join(args.output_dir, "final"))
|
| 1056 |
else:
|
| 1057 |
+
args.output_repo = in_own_account(api, args.output_repo)
|
| 1058 |
ensure_output_repo(api, args.output_repo, private=not args.public)
|
| 1059 |
|
| 1060 |
precision = resolve_precision(args.precision)
|
|
|
|
| 1186 |
"input_dataset", nargs="?",
|
| 1187 |
help="Input dataset ID. Leave out with --train-file; a single positional is then the output repo.",
|
| 1188 |
)
|
| 1189 |
+
parser.add_argument("output_repo", nargs="?", help="Output model repo: a name for your own account (my-model) or a full ID (org/my-model). Not needed with --no-push.")
|
| 1190 |
parser.add_argument("--train-file", help="Train on a local JSON Lines file (e.g. under a mounted /bucket) instead of a Hub dataset")
|
| 1191 |
parser.add_argument(
|
| 1192 |
"--eval-file", action="append",
|