Skip to content

Commit 79a8366

Browse files
davanstrienclaude
andauthored
classification: train-setfit.py — few-shot classifiers on CPU or GPU (#108)
* classification: train-setfit.py — few-shot classifiers on CPU with SetFit Adds the missing middle rung to the classification folder. The existing scripts cover zero labels (zero-shot LLM, GPU) and a few thousand labels (encoder fine-tune, GPU); SetFit covers 8-64 labels per class and runs on cpu-basic. Metrics match train-classifier.py (accuracy + macro F1 on a held-out split) so the two are directly comparable. Model card follows the repo conventions: hf jobs uv run reproduce command, JOB_ID-gated Jobs claim, org credit, uv-script + hf-jobs tags. Defaults chosen from measured runs on ag_news (8 labels/class, 500 eval, seed 42): all-MiniLM-L6-v2 (22M) cpu-basic 204s 0.826 acc / 0.819 F1 paraphrase-mpnet-base-v2 (110M) t4-small 32s 0.862 acc / 0.857 F1 paraphrase-mpnet-base-v2 (110M) cpu-basic 915s MiniLM is the default because it makes the CPU path viable (4.4x faster for 3.6pp accuracy); --body-model plus a GPU flavor gets the ceiling. Jobs logs have no TTY, so TQDM_DISABLE is set above the third-party imports (tqdm reads it at import time) and the root logger stays at WARNING. This cuts a run's log from 294 lines to 89 with no loss of signal. Verified end to end on cpu-basic and t4-small: train, evaluate, push, card, and reload from the Hub. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01U1hDrdXotHuervodDFxoD1 * classification: fix label handling, fail-fast guards, and card accuracy Acts on a review of the initial commit. Four correctness bugs, all outside the ClassLabel path that the original runs happened to exercise. Label handling (the serious one). resolve_label_names treated integer labels as VALUES while evaluate treated them as INDICES; those agree only for 0..n-1. A 1-indexed or sparse int column raised IndexError after training was already paid for, and a -1/0/1 column was worse: Python's negative indexing meant gold and predictions were wrong in matching ways, so metrics looked correct and a confidently mislabelled model was published. Index arithmetic is now confined to ClassLabel columns, which are the only integers that really are indices; every other label column is cast to string. Gold is decoded from the eval set's own feature rather than a train-derived name list, so a named --eval-split with a different ClassLabel ordering can no longer be scored against the wrong table. Note cast_column, not map: map re-casts its output back to the column's existing feature, so str() over an int64 column silently converts straight back to int64. Multi-label columns exited with a bare TypeError from set(); they now exit with a message pointing at train-classifier.py, which supports them properly. sample_dataset takes AT MOST num_samples per class, so the log and card no longer claim an exact count — both report the real per-class totals. Card: the reproduce command hardcoded --flavor cpu-basic and omitted every non-default flag, so a --body-model run published a command that trains a different model than the card describes. It is now rebuilt from the actual arguments, with the flavor derived from the accelerator. Fail-fast before the expensive call: create_repo proves write access, and a missing label column or a single-class dataset now exits immediately. Also: eval split follows train-classifier.py's validation/test precedence, which is what makes the "directly comparable" claim in the README true; the carve-out is stratified; --max-train-pool caps the pool because sample_dataset calls .to_pandas() on all of it; torch and transformers are declared in the header. Re-measured on ag_news's test split, which is a harder and more honest eval than the earlier train carve-out. MiniLM 0.804, mpnet 0.788 — the README no longer ranks them, because a 1.6pp gap at 8 examples per class is inside single-seed noise. MiniLM stays the default on speed, not accuracy. Verified on cpu-basic and t4-small; all seven single-label column shapes checked. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01U1hDrdXotHuervodDFxoD1 * classification: warn on contrastive-pair blow-up; test on four datasets SetFit builds pairs from every combination of training examples, so the count grows with the square of num_samples x classes. banking77 at 8 per class is 374,528 pairs under the default oversampling strategy — 23,408 steps, roughly 15 hours on cpu-basic — and nothing told you before the job timed out. The script now logs pairs and steps before training, and above 5,000 steps names undersampling plus its step count. The estimator's arithmetic reproduces the pair counts SetFit reports at runtime exactly (768 for ag_news, 4,312 for banking77 under undersampling). Per-class counts now go through the class names; a ClassLabel column was reporting bare indices in both the log and the card. Tested beyond ag_news, which turned out to flatter the script — every defect found in review sat outside its balanced/ClassLabel/4-class profile: enron_spam 2 classes, 16 labels, cpu-basic 0.924 acc (plain int Value label column, so this is the first live run of the cast-to-string fix) ag_news 4 classes, 32 labels, cpu-basic 0.804 acc banking77 77 classes, 616 labels, t4-small 0.803 acc (undersampling) emotion 6 classes, 48 labels, cpu-basic 0.370 acc emotion is a genuine weak spot and the README says so. Swapping the body barely moves it (bge-small 0.418, mpnet 0.410), while SetFit's docs report 0.591 on it with no labels at all via templated examples — so few-shot is not always the right rung. The default body stays MiniLM-L6 on CPU-speed grounds only; one seed per dataset cannot rank models and the README no longer implies it can. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01U1hDrdXotHuervodDFxoD1 * classification: floor reporting, a measured time budget, and GLAM data guards Third pass, driven by testing against biglam/hansard_speech — real catalogue data broke three guards that four benchmark datasets had passed. Floor reporting. Every run now prints majority_baseline next to accuracy and says whether the model beat it. Without a floor an agent gets 0.370 on dair-ai/emotion, writes a model card and reports success. The check fires on "within noise" too, not just "below": emotion scores 0.370 against a 0.352 majority, so a naive lift>0 test passes the one genuinely broken result. Every run also carries a standing note that the majority class is the LOWER floor — templated zero-shot needs no labels at all and scores 0.591 on that dataset. Time budget, replacing the step budget. The step count cannot bound runtime: measured cost per step ranges from 0.07s (short utterances, T4) to 11.2s (long speeches, CPU), a 160x spread. A 2,055-step hansard job cleared the old 5,000-step gate and then projected to 6.4 hours. The script now encodes a real sample of the actual texts on the actual hardware and refuses above --max-minutes (default 60). Two mistakes in the first version of that, both worth 6x: it timed the first encode, so torch warmup counted as steady state, and it sampled texts[:n] instead of at random. Warmed and randomised, then calibrated against a real run (predicted 1.50 s/step vs actual 2.42), hence STEP_COST_FACTOR=5, rounded up because over-estimating only prompts an override while under-estimating defeats the gate. Missing labels. hansard carries ~9.5% blank party values, and a blank string is silently a valid class name — it was training an "" party. Blank and null label rows are now dropped with a count. Ordering. Caps run before the blank-label filter: the filter is a full scan and the caps are selects, so on a 2.4M-row corpus that ordering cost eight minutes of preflight before any training. Per-class counts go through class names rather than raw ClassLabel indices. Not fixed, because it is a property of the data rather than a defect: after cleaning, hansard has 28 parties of which nine cannot supply 8 examples. The few-shot framing does not hold on that corpus at any budget. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01U1hDrdXotHuervodDFxoD1 * classification: read-through fixes and README catch-up Read the file end to end for the first time — it had grown from a dozen separate patches and had accumulated the defects that implies. - The MiniLM rationale comment had been orphaned above SCRIPT_URL by a later insertion, so it documented the wrong constant. - evaluate() still took a label_names argument it stopped using when gold decoding moved to the eval set's own feature. - The reproduce command dropped --max-train-pool, --max-eval-samples and --eval-fraction. All three change which rows are trained on or scored, so the published command reproduced a different model and a different number — the same defect as the earlier --body-model omission, fixed incompletely. - Import order and two stray blank runs. The card now discloses what makes a headline number misleading: how many classes fell short of --num-samples, whether the eval split was carved from train rather than held out, and that the majority baseline is the LOWER floor. A run on messy data can no longer report a clean-looking number quietly. README catches up with the last two commits: floor reporting, the measured time budget, blank-label dropping, the emotion counter-example, and hansard as a worked failure that produces no score. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01U1hDrdXotHuervodDFxoD1 * classification: correct the pair formula, warn on truncation, device-aware budget A subagent ran the eight guard paths that existed but had never fired in a real job. Seven passed. The eighth found an arithmetic error in my own estimator. Pair count. SetFit's shuffle_combinations defaults to replacement=True, so pair generation uses np.triu_indices(n, 0) — the diagonal is included and those self pairs all count as positive. The estimator omitted them. Checked against SetFit's own "Num unique pairs" across five runs: 2x4 -> 40 (we said 32), 4x8 unique -> 528 (496), 2x8 -> 144 (128), 3x8 -> 384, 77x8 -> 374,528. The corrected formula matches all five. Negatives are cross-class so they still exclude the diagonal, which is why the two counts are now derived separately. The error was worst at low class counts and vanished as classes grew — smallest exactly where the refusal gate binds, but in the unsafe direction. Truncation is no longer silent: the script samples documents, counts how many exceed --max-seq-length and reports the median length of those that do. Verified on enron_spam at --max-seq-length 64: "7 of 8 sampled documents exceed ... (median of those: 365 tokens)". Silent truncation is harmless on short utterances and removes the label-bearing span on long documents. The step-cost factor is now device-aware. One constant could not serve both: calibrated on CPU it under-read by 40%, and on a T4 the same constant over-read by 1.75x (projected 31 min against 17.7 actual), because GPU encodes are launch-bound rather than compute-bound. At the CPU factor the 60-minute default was refusing at roughly 34 minutes of real GPU training. Also confirmed working by the same sweep, on paths never previously exercised: the multi-label exit, the missing-column exit, the eval-equals-train exit, string labels on GPU (0.9233 on enron_spam), the stratified carve-out on a train-only ClassLabel dataset, and the BELOW FLOOR warning firing correctly on a dataset where the model genuinely lost to the majority class. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01U1hDrdXotHuervodDFxoD1 * classification: fix stratify regression, reproduce flags, and warning noise Final pre-PR review pass. The stratified carve-out crashed on exactly the case it was added to protect. train_test_split(stratify_by_column=...) requires two members of every class, so a singleton class raised a bare ValueError instead of the friendly exit every other guard gives. Reproduced locally with a 3-class ClassLabel set whose third class has one member. It now falls back to an unstratified split with a warning naming the cause. None of the 27 jobs hit this: the benchmark datasets all have held-out splits, and hansard's labels are strings so stratification was never attempted. The reproduce command still omitted --max-minutes, --allow-slow-training and --private. The first two mean a card published by an overridden run quotes a command that stops at the refusal gate; the third means a private run publishes a command that creates a public repo. Third time this class of omission has been found, so the guard comment now says why these three specifically matter. The pair-count comment listed five verifications without saying that SetFit's "Num unique pairs" is post-strategy, so the 4x8 -> 528 line read as an oversampling figure when it is the unique one; under oversampling that shape is 768. The formula was right, the evidence for it was written up misleadingly. Now grouped by strategy. Warning hygiene. The zero-shot floor note fired on every run including a 0.924 spam classifier — a warning that always fires is never read and devalues the ones that matter. It already lives in the model card, which is the durable place for it, so the log copy is gone. The refusal no longer recommends undersampling to users already using it. Truncation is now measured on the training pool and the eval set rather than the few-shot slice, which could be as few as 16 texts and never covered eval documents that are truncated at predict time too. Kept deliberately: the runtime list check in check_label_column, which is probably unreachable because datasets types list columns as Sequence. It is five cheap lines and today's pattern has been that my confident reasoning about this library is wrong more often than it should be. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01U1hDrdXotHuervodDFxoD1 * classification: measure a real training step instead of guessing a constant The time budget projected from an ENCODE multiplied by a constant standing in for the backward pass. That constant needed a different value per device (5 on CPU, 3 on GPU) and each value rested on a single observation — the same one-datapoint reasoning that produced the wrong pair formula and the wrong step budget earlier today. Now it times an actual forward+backward over 2 x batch_size real texts on the hardware that will train, and the constant is deleted. Three details matter: torch.cuda.synchronize() around the timing, because CUDA is async and without it the GPU number measures the kernel launch rather than the work; a discarded warmup pass; and the median of three. Measured against real runs of the same configuration: device old constant measurement with margin cpu-basic -38% -5% +19% t4-small +175% -22% -3% The 1.25 margin covers the part of a step the measurement omits — optimizer update, pair-batch assembly, data loading. It is fitted to two observations, so it is still an estimate, but it is an estimate of a named remainder rather than of the entire backward pass. A refusal gate should over-read: the cost is an --allow-slow-training flag, the cost of under-reading is the six-hour job. The measurement is non-blocking. If it raises, the run logs a warning and skips the budget rather than refusing — which is how the first version's tensor bug was caught without killing the job that found it. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01U1hDrdXotHuervodDFxoD1 * classification: fix the step measurement's batch size and the truncation sample Three defects from a fresh review, two of them in the measurement code added an hour earlier. The truncation check re-sliced its input to the first 200 texts, so the eval documents the caller had started appending were never examined — the previous commit claimed a fix it did not deliver. Now confirmed working: on enron_spam it reports "151 of 400 sampled documents exceed --max-seq-length 256 (median of those: 515 tokens)", i.e. 38% of that corpus is being cut at the default. The step measurement sampled min(2 * batch_size, len(texts)). A real step always processes 2 * batch_size texts because pairs are drawn WITH repetition, so any run whose few-shot set is smaller than a batch measured a short step and projected it as a whole one: 2x under at 2 classes and default batch size, 4x under at --batch-size 64 on a 4x8 pool. It now draws with replacement to a full batch. The validation runs that "confirmed" the previous version used 4x8 with batch 16 — exactly 32 texts — the one shape where the error cancels. Each timed iteration now draws a fresh batch. Reusing a single sample collapsed timing noise but not batch-composition noise, and padded length drives cost. CUDA OOM during the measurement now exits with a clear message naming --batch-size and --max-seq-length instead of being swallowed by the catch-all, which left a fragmented allocator and OOMed again mid-training. Other guard failures still degrade to a warning and skip the budget. Margin raised 1.25 -> 1.35. Measured against real runs of the same config: 2-class cpu-basic, 9 steps: projected 10.81 s/step vs 8.41 actual (+28%) 4-class cpu-basic, 48 steps: projected 3.22 s/step vs 2.51 actual (+28%) 4-class t4-small, 48 steps: projected 0.074 vs 0.0875 actual (-15%) The gate now over-reads on CPU, which is the side it should err on, and is loose on GPU where a 48-step run projects to four seconds against a sixty minute budget — three orders of magnitude from binding, so its precision there decides nothing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01U1hDrdXotHuervodDFxoD1 * classification: correct stale calibration figures and the GPU rationale Documentation defects only, but both of a kind this branch has produced before. The margin comments still quoted the pre-fix measurement. Making the timed batch full-size changed the GPU number: the raw shortfall there moved from 22% to 37%, while CPU held at ~5% across two independent configs. Anyone recalibrating from the old comments would have started from stale numbers — the same defect as the pair-count comment fixed two commits ago. The reason recorded for tolerating GPU looseness was also wrong. I had written that GPU projections sit orders of magnitude from the budget; that is true of a 4-class run and false in general. Sixty minutes on a T4 is about 41,000 steps, and 200 classes at 8 per class is ~159,000 steps — close to four hours. GPU projections bind. The real justification is narrower: a 15% under-read only changes the verdict within 15% of the boundary, and the failure mode there is a job that runs modestly over the budget the user chose, not the multi-hour runaway the gate exists to prevent. args_max_seq_hint renamed to max_seq_length. It was the parameter named after the workaround that introduced it, and it owned the longest line in the file. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01U1hDrdXotHuervodDFxoD1 * fix(classification): validate SetFit data before training * fix(classification): skip blank text rows in SetFit inputs * feat(classification): add focused SetFit on Jobs skill * classification: qualify SetFit runtime and evaluation guidance * classification: clarify SetFit CPU and GPU guidance * fix(setfit): validate private outputs and preserve GPU flavor * docs(setfit): pin the reviewed recipe revision --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 1b02cc6 commit 79a8366

6 files changed

Lines changed: 1230 additions & 5 deletions

File tree

‎README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ A self-contained, pinned script is easy to run and reuse, for a few reasons:
7171

7272
**Built for agents, too.** Every recipe takes its arguments in the same `input output` order and runs from a URL, so an AI agent can pick a tool from its header and run it with no setup. On Jobs the agent runs in a sandbox: a throwaway disk, access limited to what the token's repo permissions allow, and a cost cap per job — not arbitrary code on your machine. (Hugging Face also ships an [`hf` CLI skill for agents](https://huggingface.co/docs/hub/agents-cli) for driving Jobs from an editor.) This repo also ships a ready-to-use **[`uv-recipes` agent skill](skills/uv-recipes/)** — point your agent at it to discover, run, and adapt recipes.
7373

74+
For few-shot text classification, the focused **[`setfit-on-jobs` skill](skills/setfit-on-jobs/)** prepares a small labeled sample when needed, runs SetFit on Jobs, and verifies the resulting model.
75+
7476
## Recipes
7577

7678
| Domain | What it does | On the Hub |
@@ -82,7 +84,7 @@ A self-contained, pinned script is easy to run and reuse, for a few reasons:
8284
| **embeddings** | Embed text/images (auto-batch, prompt-aware); build a searchable Lance vector DB on the Hub | [`embeddings`](https://huggingface.co/datasets/uv-scripts/embeddings) |
8385
| **embeddings & atlas** | Embed a dataset; build an interactive map | [`build-atlas`](https://huggingface.co/datasets/uv-scripts/build-atlas) |
8486
| **data processing** | Filter / dedup / stats over large datasets | [`dataset-stats`](https://huggingface.co/datasets/uv-scripts/dataset-stats) · [`deduplication`](https://huggingface.co/datasets/uv-scripts/deduplication) |
85-
| **classification** | Fine-tune an encoder classifier (LFM2.5-Encoder, ModernBERT, …) or zero-shot classify with an LLM | [`classification`](https://huggingface.co/datasets/uv-scripts/classification) |
87+
| **classification** | Fine-tune an encoder classifier (LFM2.5-Encoder, ModernBERT, …), few-shot train one with SetFit on CPU or GPU, or zero-shot classify with an LLM | [`classification`](https://huggingface.co/datasets/uv-scripts/classification) |
8688
| **dataset creation** | Turn PDFs / image URLs into Hub datasets | [`dataset-creation`](https://huggingface.co/datasets/uv-scripts/dataset-creation) · [`iiif-tiles`](https://huggingface.co/datasets/uv-scripts/iiif-tiles) |
8789
| **synthetic data** | Generate datasets with LLMs | [`synthetic-data`](https://huggingface.co/datasets/uv-scripts/synthetic-data) |
8890
| **inference** | Run any open LLM / VLM over a dataset | [`vllm`](https://huggingface.co/datasets/uv-scripts/vllm) · [`openai-oss`](https://huggingface.co/datasets/uv-scripts/openai-oss) · [`transformers-inference`](https://huggingface.co/datasets/uv-scripts/transformers-inference) |

‎classification/README.md‎

Lines changed: 129 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
viewer: false
3-
tags: [uv-script, classification, fine-tuning, vllm, structured-outputs, gpu-required, hf-jobs]
3+
tags: [uv-script, classification, fine-tuning, few-shot, setfit, vllm, structured-outputs, hf-jobs]
44
---
55

66
# Classification Scripts
@@ -10,11 +10,20 @@ Text classification on [HF Jobs](https://huggingface.co/docs/huggingface_hub/gui
1010
| Script | What it does |
1111
|--------|--------------|
1212
| [`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 |
1314
| [`classify-dataset.py`](#zero-shot-classification-classify-datasetpy) | **Zero-shot** classify a dataset with an instruction LLM (SmolLM3 + vLLM, structured outputs) |
1415
| `classify-dataset-sglang.py` | Zero-shot variant on SGLang (reasoning-aware `<think>` models) |
1516

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.
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.
1827

1928
## Fine-tune a classifier (`train-classifier.py`)
2029

@@ -65,6 +74,123 @@ produces a plain, vLLM-servable model — pair it with
6574
[`uv-scripts/vllm`](https://huggingface.co/datasets/uv-scripts/vllm)'s
6675
`classify-dataset.py` for large-scale batch inference with the model you just trained.
6776

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+
68194
---
69195

70196
# Zero-shot classification (`classify-dataset.py`)

0 commit comments

Comments
 (0)