Repository navigation
Commit 79a8366
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
- classification
- skills
- setfit-on-jobs
- uv-recipes
- tests
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
71 | 71 | | |
72 | 72 | | |
73 | 73 | | |
| 74 | + | |
| 75 | + | |
74 | 76 | | |
75 | 77 | | |
76 | 78 | | |
| |||
82 | 84 | | |
83 | 85 | | |
84 | 86 | | |
85 | | - | |
| 87 | + | |
86 | 88 | | |
87 | 89 | | |
88 | 90 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | | - | |
| 3 | + | |
4 | 4 | | |
5 | 5 | | |
6 | 6 | | |
| |||
10 | 10 | | |
11 | 11 | | |
12 | 12 | | |
| 13 | + | |
13 | 14 | | |
14 | 15 | | |
15 | 16 | | |
16 | | - | |
17 | | - | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
18 | 27 | | |
19 | 28 | | |
20 | 29 | | |
| |||
65 | 74 | | |
66 | 75 | | |
67 | 76 | | |
| 77 | + | |
| 78 | + | |
| 79 | + | |
| 80 | + | |
| 81 | + | |
| 82 | + | |
| 83 | + | |
| 84 | + | |
| 85 | + | |
| 86 | + | |
| 87 | + | |
| 88 | + | |
| 89 | + | |
| 90 | + | |
| 91 | + | |
| 92 | + | |
| 93 | + | |
| 94 | + | |
| 95 | + | |
| 96 | + | |
| 97 | + | |
| 98 | + | |
| 99 | + | |
| 100 | + | |
| 101 | + | |
| 102 | + | |
| 103 | + | |
| 104 | + | |
| 105 | + | |
| 106 | + | |
| 107 | + | |
| 108 | + | |
| 109 | + | |
| 110 | + | |
| 111 | + | |
| 112 | + | |
| 113 | + | |
| 114 | + | |
| 115 | + | |
| 116 | + | |
| 117 | + | |
| 118 | + | |
| 119 | + | |
| 120 | + | |
| 121 | + | |
| 122 | + | |
| 123 | + | |
| 124 | + | |
| 125 | + | |
| 126 | + | |
| 127 | + | |
| 128 | + | |
| 129 | + | |
| 130 | + | |
| 131 | + | |
| 132 | + | |
| 133 | + | |
| 134 | + | |
| 135 | + | |
| 136 | + | |
| 137 | + | |
| 138 | + | |
| 139 | + | |
| 140 | + | |
| 141 | + | |
| 142 | + | |
| 143 | + | |
| 144 | + | |
| 145 | + | |
| 146 | + | |
| 147 | + | |
| 148 | + | |
| 149 | + | |
| 150 | + | |
| 151 | + | |
| 152 | + | |
| 153 | + | |
| 154 | + | |
| 155 | + | |
| 156 | + | |
| 157 | + | |
| 158 | + | |
| 159 | + | |
| 160 | + | |
| 161 | + | |
| 162 | + | |
| 163 | + | |
| 164 | + | |
| 165 | + | |
| 166 | + | |
| 167 | + | |
| 168 | + | |
| 169 | + | |
| 170 | + | |
| 171 | + | |
| 172 | + | |
| 173 | + | |
| 174 | + | |
| 175 | + | |
| 176 | + | |
| 177 | + | |
| 178 | + | |
| 179 | + | |
| 180 | + | |
| 181 | + | |
| 182 | + | |
| 183 | + | |
| 184 | + | |
| 185 | + | |
| 186 | + | |
| 187 | + | |
| 188 | + | |
| 189 | + | |
| 190 | + | |
| 191 | + | |
| 192 | + | |
| 193 | + | |
68 | 194 | | |
69 | 195 | | |
70 | 196 | | |
| |||
0 commit comments