davanstrien HF Staff commited on
Commit
28fbbeb
·
verified ·
1 Parent(s): 1017e80

Sync from GitHub via hub-sync

Browse files
Files changed (2) hide show
  1. README.md +129 -3
  2. train-setfit.py +867 -0
README.md CHANGED
@@ -1,6 +1,6 @@
1
  ---
2
  viewer: false
3
- tags: [uv-script, classification, fine-tuning, vllm, structured-outputs, gpu-required, hf-jobs]
4
  ---
5
 
6
  # Classification Scripts
@@ -10,11 +10,20 @@ Text classification on [HF Jobs](https://huggingface.co/docs/huggingface_hub/gui
10
  | Script | What it does |
11
  |--------|--------------|
12
  | [`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 |
 
13
  | [`classify-dataset.py`](#zero-shot-classification-classify-datasetpy) | **Zero-shot** classify a dataset with an instruction LLM (SmolLM3 + vLLM, structured outputs) |
14
  | `classify-dataset-sglang.py` | Zero-shot variant on SGLang (reasoning-aware `<think>` models) |
15
 
16
- Rule of thumb: zero-shot to bootstrap labels or for one-off jobs; fine-tune when you have
17
- (or have bootstrapped) a few thousand labels and want a small, fast, dedicated model.
 
 
 
 
 
 
 
 
18
 
19
  ## Fine-tune a classifier (`train-classifier.py`)
20
 
@@ -65,6 +74,123 @@ produces a plain, vLLM-servable model — pair it with
65
  [`uv-scripts/vllm`](https://huggingface.co/datasets/uv-scripts/vllm)'s
66
  `classify-dataset.py` for large-scale batch inference with the model you just trained.
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  ---
69
 
70
  # Zero-shot classification (`classify-dataset.py`)
 
1
  ---
2
  viewer: false
3
+ tags: [uv-script, classification, fine-tuning, few-shot, setfit, vllm, structured-outputs, hf-jobs]
4
  ---
5
 
6
  # Classification Scripts
 
10
  | Script | What it does |
11
  |--------|--------------|
12
  | [`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 |
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
 
17
+ Pick by how many labels you have:
18
+
19
+ | Labels you have | Use | Hardware |
20
+ |---|---|---|
21
+ | none | `classify-dataset.py` to bootstrap labels, or for one-off jobs | GPU |
22
+ | ~8-64 per class | `train-setfit.py` | CPU supported; GPU for faster training |
23
+ | a few thousand | `train-classifier.py` | GPU |
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
  ## Fine-tune a classifier (`train-classifier.py`)
29
 
 
74
  [`uv-scripts/vllm`](https://huggingface.co/datasets/uv-scripts/vllm)'s
75
  `classify-dataset.py` for large-scale batch inference with the model you just trained.
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.
82
+
83
+ **Runs on CPU or GPU.** CPU is practical for small few-shot experiments. Use a GPU for faster
84
+ training, particularly with larger models, longer texts or more classes. The same model and
85
+ training settings work on either; the recipe uses the available accelerator automatically.
86
+
87
+ - **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`.
88
+ - **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.
89
+ - **Single-label only.** A multi-label column exits with a pointer to `train-classifier.py`.
90
+ - **Metrics match `train-classifier.py`** (accuracy + macro F1). Match evaluation rows and preprocessing when comparing runs.
91
+ - **`--num-samples`** sets labelled examples per class (default 8). **`--sampling-strategy`** controls contrastive pairing: `oversampling` (default), `undersampling`, `unique`.
92
+ - **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.
93
+ - **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.
94
+ - **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.
95
+ - **`--private` verifies the output repository is private before training.** If the destination already exists publicly, choose a new repo or change its visibility first.
96
+
97
+ ```bash
98
+ # 8 labels per class, on CPU
99
+ hf jobs uv run --flavor cpu-basic --timeout 20m --secrets HF_TOKEN \
100
+ https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-setfit.py \
101
+ fancyzhx/ag_news username/ag-news-setfit --num-samples 8
102
+
103
+ # Same model and training settings on a GPU for faster training
104
+ hf jobs uv run --flavor t4-small --timeout 20m --secrets HF_TOKEN \
105
+ https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-setfit.py \
106
+ fancyzhx/ag_news username/ag-news-setfit-gpu --num-samples 8
107
+ ```
108
+
109
+ ### Choosing another body or longer context
110
+
111
+ `--body-model` accepts a Sentence Transformer checkpoint. Set `--max-seq-length` within that
112
+ model's supported context window; increasing it cannot extend a model's native limit or restore
113
+ text already shortened during dataset preparation. Longer sequences can need a smaller
114
+ `--batch-size` or more GPU memory. The recipe measures training cost on the selected hardware.
115
+
116
+ Follow the body's task-prefix instructions when preparing inputs. For example,
117
+ [`nomic-ai/modernbert-embed-base`](https://huggingface.co/nomic-ai/modernbert-embed-base)
118
+ uses Nomic's task prefixes: classification inputs should begin with `classification: `.
119
+ Include the same prefix during training, evaluation and inference. The recipe does not add it
120
+ automatically. Retain the original texts and the preprocessing details with the model.
121
+
122
+ ### Measured
123
+
124
+ 8 labels per class, seed 42, evaluated on each dataset's own held-out split (capped at 500
125
+ examples, 1000 for banking77):
126
+
127
+ | Dataset | Classes | Labels used | Body | Flavor | Training | Accuracy | Macro F1 |
128
+ |---|---|---|---|---|---|---|---|
129
+ | [`SetFit/enron_spam`](https://huggingface.co/datasets/SetFit/enron_spam) | 2 | 16 | MiniLM-L6 | `cpu-basic` | 78s | 0.924 | 0.924 |
130
+ | [`fancyzhx/ag_news`](https://huggingface.co/datasets/fancyzhx/ag_news) | 4 | 32 | MiniLM-L6 | `cpu-basic` | 118s | 0.804 | 0.807 |
131
+ | [`legacy-datasets/banking77`](https://huggingface.co/datasets/legacy-datasets/banking77) | 77 | 616 | MiniLM-L6 | `t4-small` | 18s | 0.803 | 0.789 |
132
+ | [`dair-ai/emotion`](https://huggingface.co/datasets/dair-ai/emotion) | 6 | 48 | MiniLM-L6 | `cpu-basic` | 216s | 0.370 | 0.325 |
133
+
134
+ **Single seed each — these do not rank models or predict your dataset.** Few-shot results vary
135
+ substantially with which examples happen to get sampled; SetFit's own benchmarks report mean and
136
+ standard deviation across ten seeds for exactly this reason. Run your own task before trusting
137
+ any of these numbers.
138
+
139
+ ### Compare more than the majority baseline
140
+
141
+ The `emotion` run reached **0.370** accuracy against a **0.352** majority baseline. Other
142
+ single-seed body-model runs reached 0.418 (`bge-small`) and 0.410 (`paraphrase-mpnet-base-v2`).
143
+ These results call for further evaluation; they do not establish a limit on the task or method.
144
+
145
+ SetFit's [zero-shot guide](https://huggingface.co/docs/setfit/how_to/zero_shot) reports **0.591**
146
+ on emotion using BGE and training examples templated from the class names. It uses a different
147
+ evaluation setup from the table above, so this is motivation for a matched comparison rather
148
+ than a controlled comparison with this recipe. Templated training needs no labeled documents,
149
+ but still uses compute.
150
+
151
+ For your task, compare with a simple baseline such as TF-IDF plus logistic regression using
152
+ the same training and evaluation rows. A zero-shot comparison can also be useful when class
153
+ names describe the task well. Use repeated seeds and appropriate task metrics before drawing
154
+ conclusions from small accuracy differences. This recipe trains and evaluates a supervised
155
+ classifier; built-in templated zero-shot training is a separate possible extension.
156
+
157
+ ### Real-world data: a worked failure
158
+
159
+ `biglam/hansard_speech` (2.7M parliamentary speeches, predicting `party` from `speech`) is the
160
+ case where none of the convenient properties hold, and it is instructive precisely because it
161
+ produces no score:
162
+
163
+ - **No held-out split**, so the eval set has to be carved from train — the numbers stop being
164
+ comparable to anything published.
165
+ - **~9.5% of rows have a blank `party`**, which without the drop trains an `""` class.
166
+ - **28 parties after cleaning, nine of which cannot supply 8 examples** (`Respect` 4,
167
+ `Independent SDP` 2, `Change UK` 1). The requested eight-example budget cannot be met for those classes.
168
+ - **1,878 steps at ~11s/step on CPU** — the script refuses it, projecting well past an hour.
169
+
170
+ On completed runs, the model card discloses a carved evaluation split, per-class training counts
171
+ and classes below the requested sample count. Dropped-row counts and measured truncation are
172
+ reported in the logs; retain those logs alongside the model when documenting data preparation.
173
+
174
+ ### Many classes: watch the pair count
175
+
176
+ SetFit trains on pairs drawn from every combination of training examples, so the pair count grows
177
+ with the **square** of the training-set size — which is `--num-samples` x number of classes. The
178
+ script logs the estimate before training starts:
179
+
180
+ | Dataset | Strategy | Pairs | Steps |
181
+ |---|---|---|---|
182
+ | ag_news (4 classes x 8) | `oversampling` (default) | 768 | 48 |
183
+ | banking77 (77 classes x 8) | `oversampling` (default) | 374,528 | 23,408 |
184
+ | banking77 (77 classes x 8) | `undersampling` | 4,312 | 270 |
185
+
186
+ At 77 classes the default would take roughly 15 hours on `cpu-basic`; `--sampling-strategy
187
+ undersampling` finished in 18 seconds on a T4 in the recorded run. The script reports the pair
188
+ and step counts, then measures step time to check `--max-minutes`. When it refuses training,
189
+ it suggests undersampling where applicable and estimates whether that would fit the budget.
190
+
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`)
train-setfit.py ADDED
@@ -0,0 +1,867 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "setfit>=1.2.0",
5
+ # "datasets>=4.0.0",
6
+ # "scikit-learn",
7
+ # "huggingface-hub",
8
+ # "torch",
9
+ # "transformers",
10
+ # ]
11
+ # ///
12
+ """
13
+ Few-shot text classification with SetFit — train on 8-64 labelled examples per class, on CPU or GPU.
14
+
15
+ SetFit fine-tunes a sentence-transformer body with contrastive pairs, then fits a logistic
16
+ regression head on the embeddings. It supports small labelled datasets between zero-shot LLM
17
+ labelling and a full encoder fine-tune (`train-classifier.py`). CPU is practical for small
18
+ experiments; use a GPU for faster training, particularly with larger models, longer texts or
19
+ more classes.
20
+
21
+ Run a small experiment on HF Jobs:
22
+
23
+ hf jobs uv run --flavor cpu-basic --secrets HF_TOKEN \\
24
+ https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-setfit.py \\
25
+ fancyzhx/ag_news username/ag-news-setfit \\
26
+ --num-samples 8
27
+
28
+ For faster training with the same model and settings, change --flavor to t4-small.
29
+
30
+ Metrics match `train-classifier.py` (accuracy + macro F1 on a held-out split) so the two are
31
+ directly comparable at equal eval settings.
32
+
33
+ NOTE: a SetFit model is a sentence-transformer body plus a scikit-learn head. It loads with
34
+ `SetFitModel.from_pretrained(repo)`, NOT `AutoModelForSequenceClassification`.
35
+ """
36
+
37
+ import argparse
38
+ import logging
39
+ import os
40
+ import random
41
+ import sys
42
+ import time
43
+ from collections import Counter
44
+ from math import ceil, comb, isnan
45
+
46
+ # tqdm reads TQDM_DISABLE when it is imported, so this must be set before any third-party import
47
+ # pulls tqdm in — setting it later has no effect. Jobs logs have no TTY, so progress bars arrive
48
+ # as hundreds of carriage-return frames that bury the lines you actually want.
49
+ os.environ.setdefault("TQDM_DISABLE", "1")
50
+
51
+ import datasets
52
+ import torch
53
+ import transformers
54
+ from datasets import ClassLabel, Dataset, Value, load_dataset
55
+ from huggingface_hub import HfApi, ModelCard, login
56
+ from huggingface_hub.utils import disable_progress_bars
57
+ from setfit import SetFitModel, Trainer, TrainingArguments, sample_dataset
58
+ from sklearn.metrics import accuracy_score, f1_score
59
+
60
+
61
+ def configure_logging() -> logging.Logger:
62
+ """Keep Jobs logs readable.
63
+
64
+ `basicConfig(level=INFO)` sets the ROOT logger, which switches on every library's INFO
65
+ output — on Jobs that means one line per HTTP request. Root stays at WARNING here and only
66
+ this script's logger is verbose. Progress bars are disabled because Jobs logs have no TTY:
67
+ tqdm's carriage-return frames arrive as hundreds of near-identical lines.
68
+ """
69
+ logging.basicConfig(
70
+ level=logging.WARNING,
71
+ format="%(asctime)s | %(levelname)s | %(message)s",
72
+ datefmt="%H:%M:%S",
73
+ )
74
+ for noisy in ("httpx", "urllib3", "filelock", "huggingface_hub", "sentence_transformers"):
75
+ logging.getLogger(noisy).setLevel(logging.WARNING)
76
+
77
+ disable_progress_bars()
78
+ transformers.utils.logging.disable_progress_bar()
79
+ if hasattr(datasets, "disable_progress_bars"):
80
+ datasets.disable_progress_bars()
81
+
82
+ script_logger = logging.getLogger("train-setfit")
83
+ script_logger.setLevel(logging.INFO)
84
+ return script_logger
85
+
86
+
87
+ logger = configure_logging()
88
+
89
+ SCRIPT_URL = (
90
+ "https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-setfit.py"
91
+ )
92
+
93
+ # Fixed threshold for prompting review of a small gain over the majority baseline.
94
+ # This is a heuristic, not an estimate of seed variance or statistical significance.
95
+ NOISE_BAND = 0.05
96
+
97
+ # Applied to the measured step time. Covers what the measurement omits — optimizer update,
98
+ # pair-batch assembly, data loading. Raw shortfall against real runs of the same config:
99
+ # ~5% on cpu-basic (two independent configs agreed) and 37% on t4-small.
100
+ MEASUREMENT_MARGIN = 1.35
101
+
102
+
103
+ # MiniLM-L6 is the default because it makes the CPU path viable: ~4.4x faster than
104
+ # paraphrase-mpnet-base-v2 on cpu-basic (207s vs 915s for 8 examples/class on ag_news). It is
105
+ # NOT chosen on accuracy — on ag_news's test split the two scored 0.804 and 0.788 in single-seed
106
+ # runs, which do not establish a reliable ranking. Pass --body-model to try a larger body.
107
+ DEFAULT_BODY = "sentence-transformers/all-MiniLM-L6-v2"
108
+
109
+
110
+ def check_label_column(dataset: Dataset, label_column: str) -> None:
111
+ """Fail early and clearly on a missing or multi-label column."""
112
+ if not len(dataset):
113
+ sys.exit("Dataset split is empty. Supply a non-empty labelled split.")
114
+ if label_column not in dataset.column_names:
115
+ sys.exit(
116
+ f"Label column '{label_column}' not found. Columns are: {dataset.column_names}. "
117
+ "Pass --label-column."
118
+ )
119
+
120
+ # A Sequence/list feature carries an inner `feature`; that is the multi-label shape.
121
+ feature = dataset.features.get(label_column)
122
+ if getattr(feature, "feature", None) is not None:
123
+ sys.exit(
124
+ f"Label column '{label_column}' is multi-label (a list per row). "
125
+ "train-setfit.py is single-label only — use train-classifier.py, which "
126
+ "auto-detects multi-label and tunes per-label thresholds."
127
+ )
128
+ if isinstance(dataset[label_column][0], list):
129
+ sys.exit(
130
+ f"Label column '{label_column}' holds lists (multi-label). "
131
+ "Use train-classifier.py instead."
132
+ )
133
+
134
+
135
+ def normalise_label_column(dataset: Dataset, label_column: str) -> Dataset:
136
+ """Make the label column safe for SetFit's positional label mapping.
137
+
138
+ SetFit maps an integer prediction through `model.labels` BY POSITION, so integers are only
139
+ safe when they really are indices — which is true for a ClassLabel column and nothing else.
140
+ Any other integer column holds arbitrary values (1-indexed, sparse, or negative), so it is
141
+ stringified and the head learns the label text directly. Without this, a -1/0/1 column
142
+ decodes through Python's negative indexing and silently mislabels everything while the
143
+ metrics still look correct.
144
+ """
145
+ feature = dataset.features.get(label_column)
146
+ if isinstance(feature, ClassLabel):
147
+ return dataset
148
+ # cast_column, not map: map re-casts its output back to the column's EXISTING feature, so
149
+ # returning str() from a map over an int64 column silently converts straight back to int64.
150
+ return dataset.cast_column(label_column, Value("string"))
151
+
152
+
153
+ def drop_unlabelled_rows(dataset: Dataset, label_column: str, split_name: str) -> Dataset:
154
+ """Remove rows whose label is missing or blank.
155
+
156
+ Real-world catalogue data carries missing values, and a blank string is silently a valid
157
+ class name: biglam/hansard_speech trains a "" party class unless this runs. Dropping is the
158
+ right default — an unlabelled row is not a class, and keeping it teaches the model to
159
+ predict "no label".
160
+ """
161
+ feature = dataset.features.get(label_column)
162
+
163
+ def has_label(value) -> bool:
164
+ if value is None:
165
+ return False
166
+ if isinstance(feature, ClassLabel) and value == -1:
167
+ return False
168
+ if isinstance(value, float) and isnan(value):
169
+ return False
170
+ return not (isinstance(value, str) and not value.strip())
171
+
172
+ kept = dataset.filter(has_label, input_columns=[label_column])
173
+ dropped = len(dataset) - len(kept)
174
+ if dropped:
175
+ logger.warning(
176
+ "Dropped %d %s rows with a missing or blank '%s' (%d remain).",
177
+ dropped, split_name, label_column, len(kept),
178
+ )
179
+ return kept
180
+
181
+
182
+ def prepare_split(dataset, text_column, label_column, split_name):
183
+ """Validate both splits before loading a model or paying for training."""
184
+ check_label_column(dataset, label_column)
185
+ if text_column not in dataset.column_names:
186
+ sys.exit(
187
+ f"Text column '{text_column}' not found in {split_name}. "
188
+ f"Columns are: {dataset.column_names}. Pass --text-column."
189
+ )
190
+ # Check missing labels before casting: a float NaN otherwise becomes the class "nan".
191
+ dataset = drop_unlabelled_rows(dataset, label_column, split_name)
192
+ if not len(dataset):
193
+ sys.exit(f"No labelled rows remain in {split_name} after removing missing labels.")
194
+ def has_text(text):
195
+ if text is None:
196
+ return False
197
+ if not isinstance(text, str):
198
+ sys.exit(
199
+ f"Text column '{text_column}' in {split_name} contains non-string values. "
200
+ "Clean the text column before training."
201
+ )
202
+ return bool(text.strip())
203
+
204
+ kept = dataset.filter(has_text, input_columns=[text_column])
205
+ if len(kept) < len(dataset):
206
+ logger.warning(
207
+ "Dropped %d %s rows with missing or blank '%s' (%d remain).",
208
+ len(dataset) - len(kept), split_name, text_column, len(kept),
209
+ )
210
+ if not len(kept):
211
+ sys.exit(f"No usable text rows remain in {split_name} after removing missing texts.")
212
+ return normalise_label_column(kept, label_column)
213
+
214
+
215
+ def resolve_label_names(dataset: Dataset, label_column: str) -> list[str]:
216
+ """Return the class names, in the order SetFit should map predictions through."""
217
+ feature = dataset.features.get(label_column)
218
+ if isinstance(feature, ClassLabel):
219
+ return list(feature.names)
220
+ return sorted(set(dataset[label_column]))
221
+
222
+
223
+ def pick_eval_split(dataset_id, config, train_split, requested):
224
+ """Resolve which split to evaluate on, matching train-classifier.py's precedence."""
225
+ if requested:
226
+ if requested == train_split:
227
+ sys.exit(
228
+ f"--eval-split and --train-split are both '{requested}'. Evaluating on the "
229
+ "training data would report a meaningless score."
230
+ )
231
+ return requested
232
+
233
+ # Same auto-detect order as the sibling, so both scripts evaluate on the same split by
234
+ # default and their reported metrics really are comparable.
235
+ available = datasets.get_dataset_split_names(dataset_id, config)
236
+ for candidate in ("validation", "test"):
237
+ if candidate in available and candidate != train_split:
238
+ logger.info("Using the '%s' split for evaluation.", candidate)
239
+ return candidate
240
+ return None
241
+
242
+
243
+ def split_train_eval(dataset_id, config, train_split, eval_split, eval_fraction, seed, label_column):
244
+ """Load the train split, and either the named eval split or a stratified carve-out."""
245
+ train_data = load_dataset(dataset_id, config, split=train_split)
246
+
247
+ if eval_split:
248
+ eval_data = load_dataset(dataset_id, config, split=eval_split)
249
+ return train_data, eval_data
250
+
251
+ logger.info("No eval split found; carving %.0f%% off the train split.", eval_fraction * 100)
252
+ check_label_column(train_data, label_column)
253
+ train_data = drop_unlabelled_rows(train_data, label_column, "train")
254
+ if len(train_data) < 2:
255
+ sys.exit("Need at least two labelled rows to carve out an evaluation split.")
256
+ # Encode plain labels as well, so string/int columns get the same stratification guarantee.
257
+ train_data = normalise_label_column(train_data, label_column)
258
+ if not isinstance(train_data.features[label_column], ClassLabel):
259
+ train_data = train_data.class_encode_column(label_column)
260
+
261
+ try:
262
+ parts = train_data.train_test_split(
263
+ test_size=eval_fraction, seed=seed, stratify_by_column=label_column
264
+ )
265
+ except ValueError as error:
266
+ # Stratification needs at least two members of every class, so it fails on exactly the
267
+ # singleton classes it is meant to protect. An unstratified split is worse but usable;
268
+ # crashing is not.
269
+ logger.warning(
270
+ "Could not stratify the carve-out (%s). Falling back to an unstratified split — a "
271
+ "very rare class may be absent from either split.",
272
+ error,
273
+ )
274
+ parts = train_data.train_test_split(test_size=eval_fraction, seed=seed)
275
+ return parts["train"], parts["test"]
276
+
277
+
278
+ def evaluate(model, eval_data, text_column, label_column) -> dict:
279
+ """Predict on the eval set and report the same metrics as train-classifier.py."""
280
+ # None in the text column would crash model.encode after training has already been paid for.
281
+ texts = [str(text) for text in eval_data[text_column]]
282
+ gold_raw = list(eval_data[label_column])
283
+
284
+ # The model predicts label NAMES. Decode the gold side using the EVAL set's own feature —
285
+ # a named --eval-split can order its ClassLabel differently from the train split, and
286
+ # decoding through train-derived names would silently score against the wrong table.
287
+ feature = eval_data.features.get(label_column)
288
+ if isinstance(feature, ClassLabel):
289
+ gold = [feature.int2str(int(value)) for value in gold_raw]
290
+ else:
291
+ gold = [str(value) for value in gold_raw]
292
+
293
+ started = time.time()
294
+ predictions = model.predict(texts)
295
+ elapsed = time.time() - started
296
+
297
+ # SetFit returns a tensor for int labels and a list for string labels.
298
+ if hasattr(predictions, "tolist"):
299
+ predictions = predictions.tolist()
300
+
301
+ # The majority-class rate is the floor any classifier must clear to be worth having. Without
302
+ # it a number like 0.37 reads as "a model"; against a 0.35 floor it reads as "nothing learned".
303
+ majority = Counter(gold).most_common(1)[0][1] / len(gold)
304
+
305
+ return {
306
+ "accuracy": round(accuracy_score(gold, predictions), 4),
307
+ "majority_baseline": round(majority, 4),
308
+ "f1_macro": round(f1_score(gold, predictions, average="macro", zero_division=0), 4),
309
+ "eval_examples": len(gold),
310
+ "predict_seconds": round(elapsed, 1),
311
+ }
312
+
313
+
314
+ def warn_on_truncation(model, texts, max_seq_length: int) -> None:
315
+ """Say how much of the corpus is being cut off.
316
+
317
+ Truncation is silent and its consequence is not uniform: for short utterances it never fires,
318
+ while for long documents it can remove the very span that carries the label. The 256-token
319
+ default is right for the former and wrong for the latter, so measure and report rather than
320
+ letting it be discovered in the scores.
321
+ """
322
+ tokenizer = model.model_body.tokenizer
323
+ # No internal cap: the caller decides the sample, and it deliberately mixes train and eval.
324
+ # An earlier version re-sliced to the first 200 here, which meant the eval texts appended by
325
+ # the caller were never actually looked at.
326
+ sample = list(texts)
327
+ lengths = [
328
+ len(tokenizer.encode(text, truncation=False, add_special_tokens=True)) for text in sample
329
+ ]
330
+ over = [n for n in lengths if n > max_seq_length]
331
+ if not over:
332
+ return
333
+
334
+ median_over = sorted(over)[len(over) // 2]
335
+ logger.warning(
336
+ "%d of %d sampled documents exceed --max-seq-length %d (median of those: %d tokens). "
337
+ "Everything past the limit is discarded before training and before prediction. If the "
338
+ "signal for your labels sits late in the document, raise --max-seq-length within the "
339
+ "body model's supported context window, or choose a longer-context --body-model.",
340
+ len(over), len(sample), max_seq_length, median_over,
341
+ )
342
+
343
+
344
+ def measure_step_seconds(model, texts, batch_size: int) -> float:
345
+ """Time a real forward+backward on real texts, on the hardware that will train.
346
+
347
+ Earlier versions timed an ENCODE and multiplied by a constant standing in for the backward
348
+ pass. That constant had to be fitted per device (5 on CPU, 3 on GPU) and each value rested on
349
+ a single observation — the same one-datapoint reasoning that produced two other wrong guards
350
+ today. A training step is a forward and a backward over 2 x batch_size texts, so time exactly
351
+ that instead and delete the constant.
352
+
353
+ The loss here is a stand-in, not SetFit's CoSENTLoss: cost is dominated by the transformer
354
+ forward and backward over the batch, not by the scalar reduction on top.
355
+ """
356
+ body = model.model_body
357
+ device = body.device
358
+ pool = list(texts)
359
+ rng = random.Random(0)
360
+
361
+ def draw() -> list:
362
+ # A real step always sees 2 x batch_size texts because pairs are drawn WITH repetition.
363
+ # Sampling min(2*batch_size, len(pool)) instead measured a short batch whenever the
364
+ # few-shot set was smaller than a batch — a 2-class 8-shot run at the default batch size
365
+ # measured half a step and projected it as a whole one.
366
+ return rng.choices(pool, k=2 * batch_size)
367
+
368
+ def one_step(sample) -> None:
369
+ features = body.tokenize(sample)
370
+ # tokenize() does not return tensors for every key, so move only what can move.
371
+ features = {
372
+ key: value.to(device) if hasattr(value, "to") else value
373
+ for key, value in features.items()
374
+ }
375
+ embeddings = body(features)["sentence_embedding"]
376
+ embeddings.pow(2).mean().backward()
377
+ body.zero_grad(set_to_none=True)
378
+
379
+ was_training = body.training
380
+ body.train()
381
+ try:
382
+ one_step(draw()) # warmup: first pass pays kernel/thread setup, not per-step cost
383
+ timings = []
384
+ for _ in range(3):
385
+ # Draw a FRESH batch each time. Reusing one sample collapses timing noise but not
386
+ # batch-composition noise, and padded length drives cost — on a corpus mixing short
387
+ # interjections with long speeches, one unlucky draw sets the whole estimate.
388
+ sample = draw()
389
+ if torch.cuda.is_available():
390
+ torch.cuda.synchronize() # CUDA is async; without this we time the launch only
391
+ started = time.time()
392
+ one_step(sample)
393
+ if torch.cuda.is_available():
394
+ torch.cuda.synchronize()
395
+ timings.append(time.time() - started)
396
+ finally:
397
+ body.zero_grad(set_to_none=True)
398
+ if not was_training:
399
+ body.eval()
400
+
401
+ return sorted(timings)[1]
402
+
403
+
404
+ def project_training_seconds(model, texts, batch_size: int, steps: int, max_seq_length: int) -> float:
405
+ """Project total training time from a measured step.
406
+
407
+ Step count alone cannot bound runtime: measured cost per step ranged from 0.07s (short
408
+ utterances on a T4) to 11.2s (long speeches on CPU), a 160x spread driven by hardware and
409
+ document length. A 2,055-step job cleared a 5,000-step budget and then ran for six hours.
410
+ """
411
+ try:
412
+ measured = measure_step_seconds(model, texts, batch_size)
413
+ # The measurement covers forward+backward, which is most of a step but not all of it: the
414
+ # optimizer update, pair-batch assembly and data loading are not included. Raw shortfall
415
+ # against real runs of the same config, measured AFTER the full-batch fix:
416
+ # 2-class cpu-basic 8.01 vs 8.41 actual -5%
417
+ # 4-class cpu-basic 2.39 vs 2.51 actual -5%
418
+ # 4-class t4-small 0.055 vs 0.0875 -37%
419
+ # The margin leaves CPU over-reading by ~28%, which is the side a refusal gate should err
420
+ # on, and leaves GPU under-reading by ~15%. That GPU looseness is accepted, but NOT
421
+ # because GPU runs never approach the budget — 200 classes at 8/class is ~159k steps,
422
+ # nearly four hours on a T4, so they certainly do. It is accepted because a 15% under-read
423
+ # only changes the verdict within 15% of the boundary, and the failure there is a job that
424
+ # runs modestly over the budget the user set, not the multi-hour runaway this exists to
425
+ # catch. Far from the boundary the answer is the same either way.
426
+ per_step = measured * MEASUREMENT_MARGIN
427
+ logger.info(
428
+ "Measured %.3fs per training step (forward+backward); using %.3fs with margin.",
429
+ measured, per_step,
430
+ )
431
+ except torch.cuda.OutOfMemoryError:
432
+ # A step that will not fit now will not fit in training either. Fail here, cheaply and
433
+ # clearly, rather than proceeding on a fragmented allocator and OOMing mid-run.
434
+ torch.cuda.empty_cache()
435
+ sys.exit(
436
+ f"Out of GPU memory timing a single training step at --batch-size {batch_size} and "
437
+ f"--max-seq-length {max_seq_length}. Training would fail the same way. Lower "
438
+ "--batch-size or --max-seq-length, or use a larger flavor."
439
+ )
440
+ except Exception as error:
441
+ # Any other failure of the guard itself must not block a legitimate run.
442
+ if torch.cuda.is_available():
443
+ torch.cuda.empty_cache()
444
+ logger.warning("Could not time a training step (%s); skipping the time budget.", error)
445
+ return 0.0
446
+ return per_step * steps
447
+
448
+
449
+ def estimate_training_steps(per_class, batch_size, num_epochs, strategy) -> tuple[int, int]:
450
+ """Return (contrastive pairs, optimizer steps) for one run, before any training happens.
451
+
452
+ SetFit builds pairs from every combination of training examples, so the count grows with the
453
+ SQUARE of the training-set size — and the training set is num_samples x number of classes.
454
+ A 77-class dataset at 8 examples per class is 374k pairs under the default strategy, which
455
+ is hours of CPU time. Knowing that before the job starts is worth a few lines of arithmetic.
456
+ """
457
+ counts = list(per_class.values())
458
+ total = sum(counts)
459
+
460
+ # SetFit's shuffle_combinations defaults to replacement=True, i.e. np.triu_indices(n, 0) —
461
+ # the DIAGONAL is included, and those `total` self-pairs all count as positive. Negatives are
462
+ # cross-class, so they exclude the diagonal and must be computed from the combinations
463
+ # WITHOUT it. Verified against SetFit's own reported "Num unique pairs", which is the
464
+ # POST-strategy total, so the strategy matters when reading these:
465
+ # oversampling: 2x4 -> 40 · 2x8 -> 144 · 3x8 -> 384 · 4x8 -> 768 · 77x8 -> 374,528
466
+ # undersampling: 4x8 -> 288
467
+ # unique: 4x8 -> 528
468
+ same_class_pairs = sum(comb(count, 2) for count in counts)
469
+ positive = same_class_pairs + total
470
+ negative = comb(total, 2) - same_class_pairs
471
+
472
+ if strategy == "oversampling":
473
+ pairs = 2 * max(positive, negative)
474
+ elif strategy == "undersampling":
475
+ pairs = 2 * min(positive, negative)
476
+ else: # "unique"
477
+ pairs = positive + negative
478
+
479
+ steps = ceil(pairs / batch_size) * num_epochs
480
+ return pairs, steps
481
+
482
+
483
+ def build_reproduce_command(args) -> str:
484
+ """Rebuild recipe options for Jobs, preserving the recorded accelerator when available.
485
+
486
+ Only non-default flags are appended, keeping the command short while staying faithful.
487
+ Outside Jobs, the hardware flavor is a suggested default rather than an exact record.
488
+ """
489
+ flavor = "t4-small" if torch.cuda.is_available() else "cpu-basic"
490
+ accelerator = os.environ.get("ACCELERATOR", "").strip()
491
+ if os.environ.get("JOB_ID") and accelerator.lower() not in ("", "none"):
492
+ flavor = accelerator
493
+ parts = [
494
+ f"hf jobs uv run --flavor {flavor} --secrets HF_TOKEN \\",
495
+ f" {SCRIPT_URL} \\",
496
+ f" {args.input_dataset} {args.output_repo} \\",
497
+ ]
498
+
499
+ flags = []
500
+ if args.body_model != DEFAULT_BODY:
501
+ flags.append(f"--body-model {args.body_model}")
502
+ if args.dataset_config:
503
+ flags.append(f"--dataset-config {args.dataset_config}")
504
+ if args.text_column != "text":
505
+ flags.append(f"--text-column {args.text_column}")
506
+ if args.label_column != "label":
507
+ flags.append(f"--label-column {args.label_column}")
508
+ if args.train_split != "train":
509
+ flags.append(f"--train-split {args.train_split}")
510
+ if args.eval_split:
511
+ flags.append(f"--eval-split {args.eval_split}")
512
+ if args.num_samples != 8:
513
+ flags.append(f"--num-samples {args.num_samples}")
514
+ if args.num_epochs != 1:
515
+ flags.append(f"--num-epochs {args.num_epochs}")
516
+ if args.batch_size != 16:
517
+ flags.append(f"--batch-size {args.batch_size}")
518
+ if args.max_seq_length != 256:
519
+ flags.append(f"--max-seq-length {args.max_seq_length}")
520
+ if args.sampling_strategy != "oversampling":
521
+ flags.append(f"--sampling-strategy {args.sampling_strategy}")
522
+ if args.seed != 42:
523
+ flags.append(f"--seed {args.seed}")
524
+ # These three change which rows are trained on or scored, so a command without them
525
+ # reproduces a different model and a different number.
526
+ if args.max_train_pool != 200_000:
527
+ flags.append(f"--max-train-pool {args.max_train_pool}")
528
+ if args.max_eval_samples != 2000:
529
+ flags.append(f"--max-eval-samples {args.max_eval_samples}")
530
+ if args.eval_fraction != 0.1:
531
+ flags.append(f"--eval-fraction {args.eval_fraction}")
532
+ # Without these the published command either stops at the refusal gate or publishes to a
533
+ # different visibility than the run it describes.
534
+ if args.max_minutes != 60:
535
+ flags.append(f"--max-minutes {args.max_minutes}")
536
+ if args.allow_slow_training:
537
+ flags.append("--allow-slow-training")
538
+ if args.private:
539
+ flags.append("--private")
540
+
541
+ # --num-samples is the defining knob, so always show it even at its default.
542
+ if f"--num-samples {args.num_samples}" not in flags:
543
+ flags.insert(0, f"--num-samples {args.num_samples}")
544
+
545
+ parts.append(" " + " ".join(flags))
546
+ return "\n".join(parts)
547
+
548
+
549
+ def build_card(args, label_names, metrics, per_class, train_seconds, eval_split) -> str:
550
+ """Model card following the uv-scripts conventions (org credit, Jobs claim gated on JOB_ID)."""
551
+ on_jobs = os.environ.get("JOB_ID") is not None
552
+ provenance = (
553
+ "Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs) "
554
+ "with [`uv-scripts/classification`](https://huggingface.co/datasets/uv-scripts/classification)."
555
+ if on_jobs
556
+ else "Produced with [`uv-scripts/classification`](https://huggingface.co/datasets/uv-scripts/classification)."
557
+ )
558
+
559
+ tags = ["setfit", "text-classification", "few-shot", "uv-script"]
560
+ if on_jobs:
561
+ tags.append("hf-jobs")
562
+ tag_lines = "\n".join(f"- {tag}" for tag in tags)
563
+
564
+ metric_lines = "\n".join(f"| {name} | {value} |" for name, value in metrics.items())
565
+ train_size = sum(per_class.values())
566
+ counts = ", ".join(f"`{name}`: {count}" for name, count in per_class.items())
567
+
568
+ # Disclose the two things that most often make a headline number misleading.
569
+ caveats = []
570
+ short = {name: n for name, n in per_class.items() if n < args.num_samples}
571
+ if short:
572
+ caveats.append(
573
+ f"**{len(short)} of {len(per_class)} classes had fewer than {args.num_samples} "
574
+ f"examples available** ({', '.join(f'`{k}`: {v}' for k, v in short.items())}). "
575
+ "The few-shot budget was not met for those classes."
576
+ )
577
+ if not eval_split:
578
+ caveats.append(
579
+ f"**No held-out split existed, so {args.eval_fraction:.0%} was carved out of train.** "
580
+ "These numbers are not comparable with published results on this dataset."
581
+ )
582
+ caveats.append(
583
+ f"Accuracy is reported against a majority-class baseline of "
584
+ f"`{metrics['majority_baseline']}`. Also compare with a simple trained baseline on "
585
+ "the same rows, and consider a zero-shot comparison where suitable. A small "
586
+ "single-seed gain does not establish reliable improvement."
587
+ )
588
+ caveat_block = "\n".join(f"- {c}" for c in caveats)
589
+
590
+ return f"""---
591
+ tags:
592
+ {tag_lines}
593
+ library_name: setfit
594
+ pipeline_tag: text-classification
595
+ base_model: {args.body_model}
596
+ datasets:
597
+ - {args.input_dataset}
598
+ ---
599
+
600
+ # {args.output_repo.split("/")[-1]}
601
+
602
+ Few-shot text classifier trained with [SetFit](https://github.com/huggingface/setfit) on
603
+ **up to {args.num_samples} examples per class** ({train_size} training examples in total) from
604
+ [`{args.input_dataset}`](https://huggingface.co/datasets/{args.input_dataset}).
605
+
606
+ {provenance}
607
+
608
+ ## Results
609
+
610
+ | Metric | Value |
611
+ |---|---|
612
+ {metric_lines}
613
+ | training seconds | {round(train_seconds, 1)} |
614
+
615
+ ## Training examples per class
616
+
617
+ {counts}
618
+
619
+ ## Read this before trusting the numbers
620
+
621
+ {caveat_block}
622
+
623
+ ## Labels
624
+
625
+ {", ".join(f"`{name}`" for name in label_names)}
626
+
627
+ ## Use it
628
+
629
+ ```python
630
+ from setfit import SetFitModel
631
+
632
+ model = SetFitModel.from_pretrained("{args.output_repo}")
633
+ model.predict(["some text to classify"])
634
+ ```
635
+
636
+ ## Reproduction
637
+
638
+ Produced by [`train-setfit.py`]({SCRIPT_URL}) from
639
+ [`uv-scripts/classification`](https://huggingface.co/datasets/uv-scripts/classification):
640
+
641
+ ```bash
642
+ {build_reproduce_command(args)}
643
+ ```
644
+ """
645
+
646
+
647
+ def main(args) -> None:
648
+ token = args.hf_token or os.environ.get("HF_TOKEN")
649
+ if not token:
650
+ sys.exit("No HF token. Pass --hf-token or run with --secrets HF_TOKEN.")
651
+ login(token=token)
652
+
653
+ # Prove we can write the output repo BEFORE paying for training. A permissions failure
654
+ # after trainer.train() costs the whole run and leaves no artifact behind.
655
+ api = HfApi(token=token)
656
+ api.create_repo(
657
+ args.output_repo, repo_type="model", private=args.private, exist_ok=True
658
+ )
659
+ if args.private and not api.model_info(args.output_repo).private:
660
+ sys.exit(
661
+ f"Output repo '{args.output_repo}' is public. --private does not change an existing "
662
+ "repo's visibility. Choose a new output repo or make that repo private before training."
663
+ )
664
+
665
+ logger.info("Loading %s", args.input_dataset)
666
+ eval_split = pick_eval_split(
667
+ args.input_dataset, args.dataset_config, args.train_split, args.eval_split
668
+ )
669
+ train_pool, eval_data = split_train_eval(
670
+ args.input_dataset,
671
+ args.dataset_config,
672
+ args.train_split,
673
+ eval_split,
674
+ args.eval_fraction,
675
+ args.seed,
676
+ args.label_column,
677
+ )
678
+
679
+ # Cap before final validation (a carved split already needed a pass over labels).
680
+ # Both caps are O(1) selects while the blank-label filter is a full
681
+ # scan, and on a 2.4M-row corpus that ordering was eight minutes of preflight before a single
682
+ # training step. sample_dataset also calls .to_pandas() on whatever pool it is handed, which
683
+ # would OOM a cpu-basic job outright. The cap samples randomly, so a very rare class can be
684
+ # thinned by it.
685
+ if args.max_train_pool and len(train_pool) > args.max_train_pool:
686
+ train_pool = train_pool.shuffle(seed=args.seed).select(range(args.max_train_pool))
687
+ logger.info("Capped train pool at %d rows before sampling.", args.max_train_pool)
688
+ if args.max_eval_samples and len(eval_data) > args.max_eval_samples:
689
+ eval_data = eval_data.shuffle(seed=args.seed).select(range(args.max_eval_samples))
690
+ logger.info("Capped eval set at %d examples.", args.max_eval_samples)
691
+
692
+ train_pool = prepare_split(train_pool, args.text_column, args.label_column, "train")
693
+ eval_data = prepare_split(eval_data, args.text_column, args.label_column, "eval")
694
+
695
+ label_names = resolve_label_names(train_pool, args.label_column)
696
+ logger.info("Found %d classes: %s", len(label_names), label_names)
697
+ if len(set(train_pool[args.label_column])) < 2:
698
+ sys.exit(f"Fewer than two observed classes in '{args.label_column}'. A classifier needs two or more.")
699
+
700
+ train_data = sample_dataset(
701
+ train_pool, label_column=args.label_column, num_samples=args.num_samples, seed=args.seed
702
+ )
703
+ # sample_dataset takes AT MOST num_samples per class, so report what was actually drawn.
704
+ # Keys go through the class names, or a ClassLabel column reports bare indices.
705
+ counts = sorted(Counter(train_data[args.label_column]).items())
706
+ feature = train_data.features.get(args.label_column)
707
+ if isinstance(feature, ClassLabel):
708
+ # Keep the full positional label table, but disclose declared classes with no examples.
709
+ per_class = dict.fromkeys(label_names, 0)
710
+ per_class.update({feature.int2str(int(value)): count for value, count in counts})
711
+ else:
712
+ per_class = {str(value): count for value, count in counts}
713
+ logger.info("Sampled %d training examples; per class: %s", len(train_data), per_class)
714
+
715
+ pairs, steps = estimate_training_steps(
716
+ per_class, args.batch_size, args.num_epochs, args.sampling_strategy
717
+ )
718
+ logger.info(
719
+ "Contrastive pairs: %d -> %d optimizer steps (%s).", pairs, steps, args.sampling_strategy
720
+ )
721
+ logger.info("Loading body model %s", args.body_model)
722
+ model = SetFitModel.from_pretrained(args.body_model, labels=label_names)
723
+ model.model_body.max_seq_length = args.max_seq_length
724
+
725
+ # SetFit picks the accelerator itself; report what it chose so a run's logs are self-describing.
726
+ if torch.cuda.is_available():
727
+ logger.info("DEVICE: cuda (%s)", torch.cuda.get_device_name(0))
728
+ else:
729
+ logger.info("DEVICE: cpu")
730
+ logger.info("DEVICE: body model is on %s", model.model_body.device)
731
+
732
+ # Sample the POOL and the eval set, not the few-shot training slice — that slice can be
733
+ # as small as 16 texts, and eval documents are truncated at predict time too.
734
+ warn_on_truncation(
735
+ model,
736
+ list(train_pool[args.text_column][:200]) + list(eval_data[args.text_column][:200]),
737
+ args.max_seq_length,
738
+ )
739
+
740
+ projected = project_training_seconds(
741
+ model, train_data[args.text_column], args.batch_size, steps, args.max_seq_length
742
+ )
743
+ if projected:
744
+ logger.info("Projected training time: %.0f min (%d steps).", projected / 60, steps)
745
+ if projected and projected / 60 > args.max_minutes and not args.allow_slow_training:
746
+ _, cheaper_steps = estimate_training_steps(
747
+ per_class, args.batch_size, args.num_epochs, "undersampling"
748
+ )
749
+ cheaper_minutes = projected / 60 * cheaper_steps / max(steps, 1)
750
+ if args.sampling_strategy == "undersampling":
751
+ suggestion = " (already on the cheapest sampling strategy)"
752
+ elif cheaper_minutes <= args.max_minutes:
753
+ suggestion = (
754
+ f" --sampling-strategy undersampling -> {cheaper_steps} steps "
755
+ f"(~{cheaper_minutes:.0f} min, within budget)"
756
+ )
757
+ else:
758
+ suggestion = (
759
+ f" --sampling-strategy undersampling -> {cheaper_steps} steps "
760
+ f"(~{cheaper_minutes:.0f} min — still over budget on this hardware)"
761
+ )
762
+ sys.exit(
763
+ f"Refusing to start: projected {projected / 60:.0f} min of training exceeds "
764
+ f"--max-minutes ({args.max_minutes}).\n"
765
+ f"Measured on this hardware with your actual texts, so it accounts for both the pair "
766
+ f"count and how long your documents are.\n"
767
+ f"{suggestion}\n"
768
+ f" or lower --num-samples / --max-seq-length, use a GPU flavor, "
769
+ f"or pass --allow-slow-training."
770
+ )
771
+
772
+ training_args = TrainingArguments(
773
+ batch_size=args.batch_size,
774
+ num_epochs=args.num_epochs,
775
+ seed=args.seed,
776
+ sampling_strategy=args.sampling_strategy,
777
+ report_to="none",
778
+ show_progress_bar=False,
779
+ logging_steps=10,
780
+ )
781
+ trainer = Trainer(
782
+ model=model,
783
+ args=training_args,
784
+ train_dataset=train_data,
785
+ column_mapping={args.text_column: "text", args.label_column: "label"},
786
+ )
787
+
788
+ started = time.time()
789
+ trainer.train()
790
+ train_seconds = time.time() - started
791
+ logger.info("Training finished in %.1fs", train_seconds)
792
+
793
+ metrics = evaluate(model, eval_data, args.text_column, args.label_column)
794
+ logger.info("Metrics: %s", metrics)
795
+
796
+ # A majority baseline is a useful first comparison. A small gain triggers review;
797
+ # the fixed threshold does not determine whether the difference is significant.
798
+ lift = metrics["accuracy"] - metrics["majority_baseline"]
799
+ if lift <= 0:
800
+ logger.warning(
801
+ "BELOW FLOOR: accuracy %.3f does not beat always predicting the majority class "
802
+ "(%.3f). This model is not worth deploying.",
803
+ metrics["accuracy"], metrics["majority_baseline"],
804
+ )
805
+ elif lift < NOISE_BAND:
806
+ logger.warning(
807
+ "SMALL GAIN OVER BASELINE: accuracy %.3f versus a %.3f majority class is only %.1f "
808
+ "points, below the %.0f-point review threshold. This threshold is a heuristic, "
809
+ "not a significance test. Evaluate other seeds and matched baselines before "
810
+ "drawing conclusions.",
811
+ metrics["accuracy"], metrics["majority_baseline"], lift * 100, NOISE_BAND * 100,
812
+ )
813
+ else:
814
+ logger.info("Beats the majority-class floor by %.1f points.", lift * 100)
815
+
816
+
817
+ logger.info("Pushing to %s (private=%s)", args.output_repo, args.private)
818
+ model.push_to_hub(args.output_repo, private=args.private, token=token)
819
+ card = build_card(args, label_names, metrics, per_class, train_seconds, eval_split)
820
+ ModelCard(card).push_to_hub(args.output_repo, token=token)
821
+
822
+ logger.info("Verifying reload from the Hub")
823
+ reloaded = SetFitModel.from_pretrained(args.output_repo, token=token)
824
+ sample_texts = eval_data[args.text_column][:4]
825
+ logger.info("Reloaded predictions: %s", reloaded.predict(sample_texts))
826
+ logger.info("Done: https://huggingface.co/%s", args.output_repo)
827
+
828
+
829
+ def parse_args():
830
+ parser = argparse.ArgumentParser(description="Few-shot text classification with SetFit")
831
+ parser.add_argument("input_dataset", help="Input dataset ID")
832
+ parser.add_argument("output_repo", help="Output model repo ID (username/model-name)")
833
+ parser.add_argument("--body-model", default=DEFAULT_BODY, help=f"Sentence-transformer body (default: {DEFAULT_BODY})")
834
+ parser.add_argument("--dataset-config", help="Dataset config name")
835
+ parser.add_argument("--text-column", default="text", help="Text column (default: text)")
836
+ parser.add_argument("--label-column", default="label", help="Label column (default: label)")
837
+ parser.add_argument("--train-split", default="train", help="Train split (default: train)")
838
+ parser.add_argument(
839
+ "--eval-split",
840
+ help="Eval split. Default: validation, else test, else carve --eval-fraction off "
841
+ "train. A slice such as train[:10%%] is NOT checked for overlap with training.",
842
+ )
843
+ parser.add_argument("--eval-fraction", type=float, default=0.1, help="Eval fraction if no eval split (default: 0.1)")
844
+ parser.add_argument("--max-eval-samples", type=int, default=2000, help="Cap eval examples (default: 2000)")
845
+ parser.add_argument(
846
+ "--max-train-pool", type=int, default=200_000,
847
+ help="Cap the pool before per-class sampling (default: 200000)",
848
+ )
849
+ parser.add_argument("--num-samples", type=int, default=8, help="Labelled examples per class (default: 8)")
850
+ parser.add_argument("--num-epochs", type=int, default=1, help="Epochs (default: 1)")
851
+ parser.add_argument("--sampling-strategy", default="oversampling",
852
+ choices=["oversampling", "undersampling", "unique"],
853
+ help="Contrastive pair sampling (default: oversampling)")
854
+ parser.add_argument("--batch-size", type=int, default=16, help="Batch size (default: 16)")
855
+ parser.add_argument("--max-seq-length", type=int, default=256, help="Max sequence length (default: 256)")
856
+ parser.add_argument("--seed", type=int, default=42, help="Seed (default: 42)")
857
+ parser.add_argument("--max-minutes", type=int, default=60,
858
+ help="Refuse to start if projected training exceeds this (default: 60)")
859
+ parser.add_argument("--allow-slow-training", action="store_true",
860
+ help="Override the --max-minutes refusal")
861
+ parser.add_argument("--private", action="store_true", help="Make the output model repo private")
862
+ parser.add_argument("--hf-token", help="HF token (or set HF_TOKEN)")
863
+ return parser.parse_args()
864
+
865
+
866
+ if __name__ == "__main__":
867
+ main(parse_args())