Sync from GitHub via hub-sync
Browse filesFiles changed (2)
- README.md+66-2
- train-classifier.pyAdded+814
1233456678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273---viewer: falsetags: [uv-script, classification, vllm, structured-outputs, gpu-required, hf-jobs]tags: [uv-script, classification, fine-tuning, vllm, structured-outputs, gpu-required, hf-jobs]---
# Dataset Classification Script# Classification Scripts
Text classification on [HF Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs) — both directions:
| Script | What it does ||--------|--------------|| [`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 || [`classify-dataset.py`](#zero-shot-classification-classify-datasetpy) | **Zero-shot** classify a dataset with an instruction LLM (SmolLM3 + vLLM, structured outputs) || `classify-dataset-sglang.py` | Zero-shot variant on SGLang (reasoning-aware `<think>` models) |
Rule of thumb: zero-shot to bootstrap labels or for one-off jobs; fine-tune when you have(or have bootstrapped) a few thousand labels and want a small, fast, dedicated model.
## Fine-tune a classifier (`train-classifier.py`)
Fine-tunes a text-classification encoder on any Hub dataset and pushes the trained modelback to the Hub — download, train, evaluate, push, and reload-verify in one job.
- **Default model**: [LiquidAI/LFM2.5-Encoder-350M](https://huggingface.co/LiquidAI/LFM2.5-Encoder-350M) — a bidirectional encoder that beats ModernBERT-base on GLUE/SuperGLUE and handles 8,192-token documents. Any Hub encoder works via `--model` (ModernBERT, BERT, DeBERTa, …).- **Single-label and multi-label**, auto-detected from the label column (`ClassLabel`/string/int → cross-entropy; list of labels → BCE + per-label threshold tuning).- **Round-trippable artifacts**: standard architectures produce standard models; encoders without a classification head (like LFM2.5) get a generic mean-pooling head pushed as custom code, so `AutoModelForSequenceClassification.from_pretrained(..., trust_remote_code=True)` always works.
```bash# single-label (ag_news has a ClassLabel column)hf jobs uv run --flavor a10g-small --secrets HF_TOKEN \ https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-classifier.py \ fancyzhx/ag_news username/news-classifier
# multi-label (go_emotions has a list-of-labels column)hf jobs uv run --flavor a10g-small --secrets HF_TOKEN \ https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-classifier.py \ google-research-datasets/go_emotions username/emotion-classifier --label-column labels```
Key options: `--model`, `--max-length` (512 default; up to 8192 with`--gradient-checkpointing` and a small `--batch-size` on a10g/a100), `--epochs`, `--lr`,`--batch-size`, `--max-samples` (smoke runs), `--eval-split` (auto-detectsvalidation/test, or holds out 10% of train). Run `uv run train-classifier.py --help` for all.
### Worked example: classify dataset cards by task
[`davanstrien/dataset-cards-with-task-categories`](https://huggingface.co/datasets/davanstrien/dataset-cards-with-task-categories)contains 21k Hub dataset cards (frontmatter stripped) labelled with their `task_categories`metadata — a real multi-label task over long documents:
```bashhf jobs uv run --flavor a10g-small --secrets HF_TOKEN \ https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-classifier.py \ davanstrien/dataset-cards-with-task-categories username/dataset-card-task-classifier \ --label-column labels --max-length 1024 --batch-size 8 --grad-accum 2```
The output model predicts likely task categories from a card's prose — e.g. for suggestingmetadata on datasets that lack it.
### Training a standard encoder instead
`--model answerdotai/ModernBERT-base` (or any encoder with a native classification head)produces a plain, vLLM-servable model — pair it with[`uv-scripts/vllm`](https://huggingface.co/datasets/uv-scripts/vllm)'s`classify-dataset.py` for large-scale batch inference with the model you just trained.
---
# Zero-shot classification (`classify-dataset.py`)
GPU-accelerated text classification for Hugging Face datasets with guaranteed valid outputs through structured generation. Powered by SmolLM3-3B's advanced reasoning capabilities.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814# /// script# requires-python = ">=3.11"# dependencies = [# "datasets>=4.0.0",# "transformers>=5.12",# "torch",# "accelerate",# "safetensors",# "scikit-learn",# "numpy",# "huggingface-hub",# ]# ///"""Fine-tune a text-classification encoder on a Hub dataset and push the trained model to the Hub.
Defaults to LiquidAI's LFM2.5-Encoder-350M — a bidirectional encoder converted from an LFM2decoder backbone (blog: https://huggingface.co/blog/LiquidAI/lfm2-5-encoders). The 230M variantbeats ModernBERT-base on GLUE/SuperGLUE and both handle 8,192-token documents, so long inputs(dataset cards, legal documents, support threads) fit without chunking. Any Hub encoder worksvia --model: models with a standard sequence-classification head (BERT, ModernBERT, DeBERTa, …)train through `AutoModelForSequenceClassification` and produce standard artifacts; modelswithout one (like the LFM2.5 encoders) get a generic mean-pooling + linear head that is pushedas custom code, so the output still round-trips through`AutoModelForSequenceClassification.from_pretrained(..., trust_remote_code=True)`.
Single-label vs multi-label is auto-detected from the label column:
- `ClassLabel` / string / int column -> single-label (cross-entropy)- `Sequence(ClassLabel)` / list of strings -> multi-label (BCE + per-label threshold tuning)
Run on HF Jobs (l4x1 is enough for 512-token contexts; the model is downloaded, trained,evaluated, pushed, and reload-verified in one job):
hf jobs uv run --flavor l4x1 --secrets HF_TOKEN \\ https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-classifier.py \\ fancyzhx/ag_news username/my-news-classifier \\ --max-samples 2000 --epochs 1
Multi-label example (go_emotions has a Sequence(ClassLabel) `labels` column):
hf jobs uv run --flavor l4x1 --secrets HF_TOKEN \\ https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-classifier.py \\ google-research-datasets/go_emotions username/my-emotion-classifier \\ --label-column labels
Long documents: pair --max-length 8192 with --gradient-checkpointing and a small batch size(--batch-size 2 --grad-accum 8) on a10g/a100 flavors.
Model: https://huggingface.co/LiquidAI/LFM2.5-Encoder-350M
Smoke-tested 2026-07-28 on a10g-small (transformers 5.14.1, torch 2.13.0): single-label(ag_news, acc 0.757 on a 2k/1-epoch smoke), multi-label (go_emotions, threshold tuninglifting micro-F1 0.00->0.24 on a 2k/1-epoch smoke), and the standard-architecture path(ModernBERT-base on ag_news, acc 0.871, vanilla artifact); pushed models pass the in-jobreload check and a fresh local CPU reload."""
import argparseimport importlib.utilimport jsonimport loggingimport osimport shutilimport sysimport tempfilefrom datetime import datetime, timezonefrom typing import Optional
import numpy as npimport torchfrom datasets import ClassLabel, Dataset, load_datasetfrom huggingface_hub import HfApi, ModelCard, hf_hub_download, list_repo_files, loginfrom sklearn.metrics import accuracy_score, f1_scorefrom transformers import ( AutoConfig, AutoModel, AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, Trainer, TrainingArguments,)
logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
DEFAULT_MODEL = "LiquidAI/LFM2.5-Encoder-350M"SCRIPT_URL = "https://huggingface.co/datasets/uv-scripts/classification/raw/main/train-classifier.py"WRAPPER_MODULE = "modeling_encoder_seq_cls"WRAPPER_CLASS = "EncoderForSequenceClassification"
# Generic sequence-classification wrapper for encoders whose remote code ships no# AutoModelForSequenceClassification (e.g. the LFM2.5 encoders expose only AutoModel +# AutoModelForMaskedLM). This exact file is used for training AND copied into the pushed# repo with an auto_map entry, so the training class and the reload class can never drift.MODELING_FILE = '''"""Generic sequence classification head: AutoModel backbone + mean pooling + linear.
Auto-generated by the uv-scripts `train-classifier.py` recipe. Loaded via`AutoModelForSequenceClassification.from_pretrained(repo, trust_remote_code=True)`;the backbone class is resolved from this repo's own `auto_map`/code files."""
import torchfrom torch import nnfrom transformers import AutoModel, PreTrainedModelfrom transformers.modeling_outputs import SequenceClassifierOutput
class EncoderForSequenceClassification(PreTrainedModel): base_model_prefix = "model" supports_gradient_checkpointing = True
def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.model = AutoModel.from_config(config, trust_remote_code=True) dropout = getattr(config, "classifier_dropout", None) self.dropout = nn.Dropout(0.1 if dropout is None else dropout) self.classifier = nn.Linear(config.hidden_size, config.num_labels) self.post_init()
def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs): outputs = self.model(input_ids=input_ids, attention_mask=attention_mask) hidden = outputs.last_hidden_state if attention_mask is None: pooled = hidden.mean(dim=1) else: mask = attention_mask.unsqueeze(-1).to(hidden.dtype) pooled = (hidden * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1e-9) logits = self.classifier(self.dropout(pooled)) loss = None if labels is not None: if self.config.problem_type == "multi_label_classification": loss = nn.functional.binary_cross_entropy_with_logits( logits, labels.to(logits.dtype) ) else: loss = nn.functional.cross_entropy(logits, labels.view(-1)) return SequenceClassifierOutput(loss=loss, logits=logits)
# AutoModelForSequenceClassification.from_pretrained registers this class against the# config class, and that requires config_class to be set (transformers v5 crashes on None).try: __CONFIG_IMPORT__ EncoderForSequenceClassification.config_class = __CONFIG_CLASS__except ImportError: # flat import during training; the trainer sets config_class itself pass'''
def render_modeling_file(config) -> str: """Fill the wrapper template with the backbone's concrete config class.""" config_cls = type(config) name = config_cls.__name__ if config_cls.__module__.startswith("transformers."): import_stmt = f"from transformers import {name}" else: # remote-code config: its module file is copied into the pushed repo alongside # this wrapper, where the dynamic-module loader supports relative imports module_file = config_cls.__module__.split(".")[-1] import_stmt = f"from .{module_file} import {name}" return MODELING_FILE.replace("__CONFIG_IMPORT__", import_stmt).replace( "__CONFIG_CLASS__", name )
def check_cuda_availability() -> None: if not torch.cuda.is_available(): logger.error("CUDA is not available. This script requires a GPU.") logger.error("Run on Hugging Face Jobs with: hf jobs uv run --flavor l4x1 ...") sys.exit(1) logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name()}")
# ---------------------------------------------------------------------------# Labels# ---------------------------------------------------------------------------
def detect_task(dataset: Dataset, label_column: str) -> tuple[str, list[str]]: """Return (problem_type, label_names) from the label column's feature/values.
single_label_classification: ClassLabel, string, or int column. multi_label_classification: Sequence(ClassLabel)/List(ClassLabel) or list-of-strings column. """ feature = dataset.features[label_column]
# Sequence / List / LargeList all expose .feature; ClassLabel and Value do not. inner = getattr(feature, "feature", None)
if inner is not None: if isinstance(inner, ClassLabel): return "multi_label_classification", list(inner.names) values = {v for row in dataset[label_column] for v in (row or [])} if not values: logger.error(f"Label column '{label_column}' contains only empty lists.") sys.exit(1) return "multi_label_classification", sorted(str(v) for v in values)
if isinstance(feature, ClassLabel): return "single_label_classification", list(feature.names)
values = dataset.unique(label_column) if any(v is None for v in values): logger.error(f"Label column '{label_column}' contains nulls.") sys.exit(1) if all(isinstance(v, (int, np.integer)) for v in values): return "single_label_classification", [str(v) for v in sorted(values)] if all(isinstance(v, str) for v in values): return "single_label_classification", sorted(values)
logger.error( f"Unsupported label column '{label_column}' " f"(feature: {feature}). Supported: ClassLabel, string, int, " f"Sequence(ClassLabel), or list-of-strings." ) sys.exit(1)
def encode_labels(example, label_column, problem_type, label2id, num_labels, ints_are_indices): """ints_are_indices: True for ClassLabel columns, where raw ints already ARE the class indices. Plain int columns (e.g. values [10, 20]) map via label2id instead.""" raw = example[label_column] if problem_type == "multi_label_classification": vec = [0.0] * num_labels for v in raw or []: if isinstance(v, str): idx = label2id[v] elif ints_are_indices: idx = int(v) else: idx = label2id[str(v)] vec[idx] = 1.0 return {"encoded_labels": vec} if isinstance(raw, str): return {"encoded_labels": label2id[raw]} if ints_are_indices: return {"encoded_labels": int(raw)} return {"encoded_labels": label2id[str(raw)]}
# ---------------------------------------------------------------------------# Model construction — ordered decision rule (order matters):# 1. auto_map has AutoModelForSequenceClassification -> custom model ships its own head# 2. auto_map exists without one (LFM2.5 encoders) -> our mean-pooling wrapper; never# fall through to the built-in mapping: a future *causal* Lfm2ForSequenceClassification# in transformers would silently load a causal-mask head onto bidirectional weights# 3. vanilla model -> standard AutoModelForSequenceClassification (standard artifact,# servable by vllm/classify-dataset.py)# ---------------------------------------------------------------------------
def build_model(model_id, problem_type, label_names, work_dir): """Return (model, tokenizer, path) where path is 'custom-shipped'|'custom-wrapper'|'standard'.""" num_labels = len(label_names) id2label = {i: name for i, name in enumerate(label_names)} label2id = {name: i for i, name in enumerate(label_names)}
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True) config = AutoConfig.from_pretrained(model_id, trust_remote_code=True) auto_map = getattr(config, "auto_map", None) or {}
label_kwargs = dict( num_labels=num_labels, id2label=id2label, label2id=label2id, problem_type=problem_type, )
if "AutoModelForSequenceClassification" in auto_map: logger.info("Model ships its own sequence-classification head (auto_map) — using it.") model = AutoModelForSequenceClassification.from_pretrained( model_id, trust_remote_code=True, **label_kwargs ) return model, tokenizer, "custom-shipped"
if auto_map: logger.info( "Custom-code model without a sequence-classification head — " "using the generic mean-pooling wrapper." ) for key, value in label_kwargs.items(): setattr(config, key, value) wrapper_path = os.path.join(work_dir, f"{WRAPPER_MODULE}.py") with open(wrapper_path, "w") as f: f.write(render_modeling_file(config)) spec = importlib.util.spec_from_file_location(WRAPPER_MODULE, wrapper_path) module = importlib.util.module_from_spec(spec) sys.modules[WRAPPER_MODULE] = module spec.loader.exec_module(module) wrapper_cls = getattr(module, WRAPPER_CLASS) wrapper_cls.config_class = type(config) model = wrapper_cls(config) # Replace the randomly-initialised backbone with the pretrained weights. model.model = AutoModel.from_pretrained(model_id, trust_remote_code=True) return model, tokenizer, "custom-wrapper"
logger.info("Standard architecture — using AutoModelForSequenceClassification.") model = AutoModelForSequenceClassification.from_pretrained(model_id, **label_kwargs) return model, tokenizer, "standard"
# ---------------------------------------------------------------------------# Metrics# ---------------------------------------------------------------------------
def make_compute_metrics(problem_type): def compute(eval_pred): logits, labels = eval_pred.predictions, eval_pred.label_ids if problem_type == "multi_label_classification": probs = 1 / (1 + np.exp(-logits)) preds = (probs >= 0.5).astype(int) return { "f1_micro": f1_score(labels, preds, average="micro", zero_division=0), "f1_macro": f1_score(labels, preds, average="macro", zero_division=0), } preds = logits.argmax(axis=-1) return { "accuracy": accuracy_score(labels, preds), "f1_macro": f1_score(labels, preds, average="macro", zero_division=0), }
return compute
def tune_thresholds(logits: np.ndarray, labels: np.ndarray) -> list[float]: """Per-label threshold sweep (0.05–0.95) maximising per-label F1 on the eval set.""" probs = 1 / (1 + np.exp(-logits)) thresholds = [] for i in range(labels.shape[1]): best_t, best_f1 = 0.5, -1.0 for t in np.arange(0.05, 0.96, 0.05): f1 = f1_score(labels[:, i], (probs[:, i] >= t).astype(int), zero_division=0) if f1 > best_f1: best_t, best_f1 = round(float(t), 2), f1 thresholds.append(best_t) return thresholds
# ---------------------------------------------------------------------------# Push + verify# ---------------------------------------------------------------------------
def assemble_output_repo(model, tokenizer, path_kind, model_id, out_dir, extra_config): """Fill out_dir with a self-contained, from_pretrained-able model.""" from safetensors.torch import save_model
tokenizer.save_pretrained(out_dir)
if path_kind != "custom-wrapper": # Standard / custom-shipped heads: transformers handles the layout natively # (custom_object_save copies remote modules for custom-shipped models). for key, value in extra_config.items(): setattr(model.config, key, value) model.save_pretrained(out_dir) return
# Custom wrapper: copy the backbone's code files so the pushed repo is self-sufficient, # then write config + weights manually (save_pretrained on a dynamically-imported class # would try to copy this whole uv script as the modeling file). for fname in list_repo_files(model_id): if fname.endswith(".py"): local = hf_hub_download(model_id, fname) shutil.copy(local, os.path.join(out_dir, os.path.basename(fname))) logger.info(f"Copied backbone code file: {fname}")
config = model.config for key, value in extra_config.items(): setattr(config, key, value) backbone_auto_map = getattr(config, "auto_map", None) or {} config.auto_map = { **backbone_auto_map, "AutoModelForSequenceClassification": f"{WRAPPER_MODULE}.{WRAPPER_CLASS}", } config.architectures = [WRAPPER_CLASS] config.save_pretrained(out_dir)
# Belt and braces: force plain module.Class refs in the saved JSON (transformers can # rewrite auto_map entries to 'origin-repo--module.Class', which would point reloads # at the origin repo instead of the pushed one). config_path = os.path.join(out_dir, "config.json") with open(config_path) as f: saved = json.load(f) saved["auto_map"] = { k: v.split("--", 1)[-1] for k, v in saved.get("auto_map", {}).items() } saved["auto_map"]["AutoModelForSequenceClassification"] = ( f"{WRAPPER_MODULE}.{WRAPPER_CLASS}" ) with open(config_path, "w") as f: json.dump(saved, f, indent=2, sort_keys=True)
save_model(model, os.path.join(out_dir, "model.safetensors"))
def verify_reload(output_repo, eval_texts, reference_preds, problem_type, max_length, hf_token): """Reload the *pushed* repo fresh and check prediction agreement. Hard-fail on mismatch.""" logger.info(f"RELOAD CHECK: loading {output_repo} back from the Hub...") tokenizer = AutoTokenizer.from_pretrained(output_repo, trust_remote_code=True, token=hf_token) model = AutoModelForSequenceClassification.from_pretrained( output_repo, trust_remote_code=True, token=hf_token ) model.eval() enc = tokenizer( eval_texts, truncation=True, max_length=max_length, padding=True, return_tensors="pt" ) with torch.no_grad(): logits = model(**enc).logits preds = logits.argmax(dim=-1).tolist() if preds != reference_preds: logger.error("RELOAD CHECK: FAILED — pushed model disagrees with trained model.") logger.error(f" in-memory: {reference_preds}") logger.error(f" reloaded: {preds}") sys.exit(1) logger.info(f"RELOAD CHECK: OK ({len(preds)}/{len(preds)} predictions agree)")
# ---------------------------------------------------------------------------# Card# ---------------------------------------------------------------------------
def build_card( input_dataset, output_repo, model_id, problem_type, label_names, metrics, thresholds, path_kind, args_summary,) -> str: on_jobs = os.environ.get("JOB_ID") is not None # set by HF Jobs in-container hw = os.environ.get("ACCELERATOR") or "" # e.g. "l4x1"; empty on CPU origin = ( "Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)" + (f" (`{hw}`)" if hw else "") ) if on_jobs else "Generated"
tags = ["uv-script", "text-classification"] if on_jobs: tags.append("hf-jobs") tag_lines = "\n".join(f"- {t}" for t in tags)
metric_rows = "\n".join(f"| {k} | {v:.4f} |" for k, v in metrics.items()) multi = problem_type == "multi_label_classification"
label_list = ", ".join(f"`{name}`" for name in label_names[:30]) if len(label_names) > 30: label_list += f", … ({len(label_names)} total)"
if multi: snippet = f"""```pythonimport torchfrom transformers import AutoModelForSequenceClassification, AutoTokenizer
model = AutoModelForSequenceClassification.from_pretrained("{output_repo}", trust_remote_code=True)tokenizer = AutoTokenizer.from_pretrained("{output_repo}", trust_remote_code=True)
inputs = tokenizer("your text here", return_tensors="pt", truncation=True)probs = torch.sigmoid(model(**inputs).logits)[0]thresholds = torch.tensor(model.config.classifier_thresholds) # tuned on validationlabels = [model.config.id2label[i] for i in (probs >= thresholds).nonzero().flatten().tolist()]print(labels)```""" else: snippet = f"""```pythonfrom transformers import AutoModelForSequenceClassification, AutoTokenizer
model = AutoModelForSequenceClassification.from_pretrained("{output_repo}", trust_remote_code=True)tokenizer = AutoTokenizer.from_pretrained("{output_repo}", trust_remote_code=True)
inputs = tokenizer("your text here", return_tensors="pt", truncation=True)print(model.config.id2label[model(**inputs).logits.argmax().item()])```"""
serving_note = "" if path_kind == "custom-wrapper": serving_note = ( "\n> [!NOTE]\n" "> This model uses a custom classification head (mean pooling over a backbone " "without a native sequence-classification class), so loading requires " "`trust_remote_code=True`. vLLM serving requires a standard architecture.\n" )
return f"""---tags:{tag_lines}base_model: {model_id}datasets:- {input_dataset}pipeline_tag: text-classificationlibrary_name: transformers---
# {output_repo.split("/")[-1]}
[{model_id}](https://huggingface.co/{model_id}) fine-tuned for{"multi-label" if multi else "single-label"} text classification on[{input_dataset}](https://huggingface.co/datasets/{input_dataset}).
- **Labels ({len(label_names)})**: {label_list}- **Date**: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}{serving_note}## Evaluation
| Metric | Value ||--------|-------|{metric_rows}{'''Per-label decision thresholds tuned on the eval split are stored in`config.classifier_thresholds`.
**Choosing an operating point**: the stored thresholds maximise per-label F1. Forprecision-first use (e.g. auto-applying labels), act only on predictions well abovetheir threshold — sigmoid probabilities are a usable confidence signal, and filteringto high-confidence predictions trades coverage for precision. Route the rest to review.''' if multi and thresholds else ""}## Usage
{snippet}
## Reproduction
{origin} with the [`train-classifier.py`]({SCRIPT_URL}) recipe from [uv-scripts](https://huggingface.co/uv-scripts). Run it yourself:
```bashhf jobs uv run --flavor {hw or "l4x1"} --secrets HF_TOKEN \\ {SCRIPT_URL} \\ {args_summary}```"""
# ---------------------------------------------------------------------------# Main# ---------------------------------------------------------------------------
def main( input_dataset: str, output_repo: str, model_id: str = DEFAULT_MODEL, dataset_config: Optional[str] = None, text_column: str = "text", label_column: str = "label", train_split: str = "train", eval_split: Optional[str] = None, eval_fraction: float = 0.1, max_samples: Optional[int] = None, seed: int = 42, max_length: int = 512, epochs: int = 3, lr: float = 2e-5, batch_size: int = 16, grad_accum: int = 1, warmup_ratio: float = 0.05, gradient_checkpointing: bool = False, no_bf16: bool = False, private: bool = False, hf_token: Optional[str] = None,) -> None: import transformers
logger.info(f"transformers {transformers.__version__} | torch {torch.__version__}") check_cuda_availability()
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN") if HF_TOKEN: login(token=HF_TOKEN)
# ----- data ----- logger.info(f"Loading dataset: {input_dataset} (config={dataset_config})") ds = load_dataset(input_dataset, dataset_config) if train_split not in ds: logger.error(f"Split '{train_split}' not found. Available: {list(ds)}") sys.exit(1) train_ds = ds[train_split]
if eval_split: if eval_split not in ds: logger.error(f"Split '{eval_split}' not found. Available: {list(ds)}") sys.exit(1) eval_ds = ds[eval_split] elif "validation" in ds: eval_ds, eval_split = ds["validation"], "validation" elif "test" in ds: eval_ds, eval_split = ds["test"], "test" else: logger.info(f"No eval split found — holding out {eval_fraction:.0%} of train.") parts = train_ds.train_test_split(test_size=eval_fraction, seed=seed) train_ds, eval_ds, eval_split = parts["train"], parts["test"], "held-out"
if label_column not in train_ds.column_names and label_column == "label" and "labels" in train_ds.column_names: logger.info("Column 'label' not found; falling back to 'labels'.") label_column = "labels" for col in (text_column, label_column): if col not in train_ds.column_names: logger.error(f"Column '{col}' not found. Columns: {train_ds.column_names}") sys.exit(1)
if max_samples: train_ds = train_ds.shuffle(seed=seed).select(range(min(max_samples, len(train_ds)))) eval_ds = eval_ds.shuffle(seed=seed).select(range(min(max_samples, len(eval_ds))))
problem_type, label_names = detect_task(train_ds, label_column) num_labels = len(label_names) label2id = {name: i for i, name in enumerate(label_names)} label_feature = train_ds.features[label_column] ints_are_indices = isinstance(label_feature, ClassLabel) or isinstance( getattr(label_feature, "feature", None), ClassLabel ) logger.info(f"Task: {problem_type} | {num_labels} labels | " f"train={len(train_ds)} eval={len(eval_ds)} ({eval_split})")
# ----- model ----- work_dir = tempfile.mkdtemp(prefix="train-classifier-") out_dir = os.path.join(work_dir, "model") os.makedirs(out_dir, exist_ok=True) model, tokenizer, path_kind = build_model(model_id, problem_type, label_names, out_dir) if gradient_checkpointing: model.gradient_checkpointing_enable()
# ----- tokenize ----- def tokenize(batch): return tokenizer( [str(t) for t in batch[text_column]], truncation=True, max_length=max_length )
keep = {"input_ids", "attention_mask", "labels"}
def prepare(split): # Encode into a TEMP column, drop the original, then rename to "labels". # Writing straight into the original column name makes datasets cast the # encoded values back to the original schema (e.g. multi-hot floats -> # list-of-strings -> the collator crashes with "excessive nesting"). split = split.map( lambda ex: encode_labels( ex, label_column, problem_type, label2id, num_labels, ints_are_indices ), remove_columns=[label_column], ) split = split.rename_column("encoded_labels", "labels") split = split.map(tokenize, batched=True) return split.remove_columns([c for c in split.column_names if c not in keep])
train_tok, eval_tok = prepare(train_ds), prepare(eval_ds)
# ----- train ----- bf16 = not no_bf16 and torch.cuda.is_bf16_supported() if not bf16: logger.warning("bf16 unavailable or disabled — training in fp32.") # save_strategy stays "no": Trainer checkpointing on the dynamically-imported wrapper # would trigger custom_object_save, which copies this whole uv script as modeling code. # The final save is manual (assemble_output_repo). training_args = TrainingArguments( output_dir=os.path.join(work_dir, "trainer"), num_train_epochs=epochs, learning_rate=lr, per_device_train_batch_size=batch_size, per_device_eval_batch_size=batch_size * 2, gradient_accumulation_steps=grad_accum, warmup_ratio=warmup_ratio, weight_decay=0.01, bf16=bf16, eval_strategy="epoch", save_strategy="no", logging_steps=10, seed=seed, report_to="none", ) trainer = Trainer( model=model, args=training_args, train_dataset=train_tok, eval_dataset=eval_tok, data_collator=DataCollatorWithPadding(tokenizer), compute_metrics=make_compute_metrics(problem_type), ) trainer.train()
# ----- final eval (+ threshold tuning for multi-label) ----- predictions = trainer.predict(eval_tok) logits, labels = predictions.predictions, predictions.label_ids metrics, thresholds = {}, None if problem_type == "multi_label_classification": probs = 1 / (1 + np.exp(-logits)) preds_05 = (probs >= 0.5).astype(int) thresholds = tune_thresholds(logits, labels) preds_tuned = (probs >= np.array(thresholds)).astype(int) metrics = { "f1_micro @ 0.5": f1_score(labels, preds_05, average="micro", zero_division=0), "f1_macro @ 0.5": f1_score(labels, preds_05, average="macro", zero_division=0), "f1_micro @ tuned": f1_score(labels, preds_tuned, average="micro", zero_division=0), "f1_macro @ tuned": f1_score(labels, preds_tuned, average="macro", zero_division=0), } else: preds = logits.argmax(axis=-1) metrics = { "accuracy": accuracy_score(labels, preds), "f1_macro": f1_score(labels, preds, average="macro", zero_division=0), } for k, v in metrics.items(): logger.info(f"eval {k}: {v:.4f}")
# ----- push ----- extra_config = {"problem_type": problem_type} if thresholds: extra_config["classifier_thresholds"] = thresholds
logger.info(f"Assembling output repo in {out_dir}") model = model.to("cpu").float() assemble_output_repo(model, tokenizer, path_kind, model_id, out_dir, extra_config)
api = HfApi(token=HF_TOKEN) api.create_repo(output_repo, repo_type="model", private=private, exist_ok=True) logger.info(f"Uploading to {output_repo}") api.upload_folder(folder_path=out_dir, repo_id=output_repo, repo_type="model")
args_summary = f"{input_dataset} {output_repo}" if model_id != DEFAULT_MODEL: args_summary += f" --model {model_id}" if label_column != "label": args_summary += f" --label-column {label_column}" card = build_card( input_dataset, output_repo, model_id, problem_type, label_names, metrics, thresholds, path_kind, args_summary, ) try: ModelCard(card).push_to_hub(output_repo, token=HF_TOKEN) except Exception as e: logger.warning(f"Could not push model card: {e}")
# ----- verify the pushed artifact round-trips ----- n_check = min(8, len(eval_ds)) check_texts = [str(t) for t in eval_ds[text_column][:n_check]] model.eval() enc = tokenizer( check_texts, truncation=True, max_length=max_length, padding=True, return_tensors="pt" ) with torch.no_grad(): reference_preds = model(**enc).logits.argmax(dim=-1).tolist() verify_reload(output_repo, check_texts, reference_preds, problem_type, max_length, HF_TOKEN)
logger.info("Done!") logger.info(f"Model: https://huggingface.co/{output_repo}")
if __name__ == "__main__": if len(sys.argv) == 1: print("Fine-tune a text-classification encoder (default: LFM2.5-Encoder-350M)") print("\nUsage:") print(" uv run train-classifier.py INPUT_DATASET OUTPUT_MODEL_REPO [options]") print("\nExamples:") print(" # single-label (ClassLabel column)") print(" uv run train-classifier.py fancyzhx/ag_news username/news-classifier") print("\n # multi-label (list-of-labels column)") print(" uv run train-classifier.py google-research-datasets/go_emotions \\") print(" username/emotion-classifier --label-column labels") print("\nFor full help: uv run train-classifier.py --help") sys.exit(0)
parser = argparse.ArgumentParser( description="Fine-tune a text-classification encoder on a Hub dataset and push to Hub", ) parser.add_argument("input_dataset", help="Input dataset ID") parser.add_argument("output_repo", help="Output model repo ID (username/model-name)") parser.add_argument("--model", default=DEFAULT_MODEL, help=f"Base model (default: {DEFAULT_MODEL})") parser.add_argument("--dataset-config", help="Dataset config name") parser.add_argument("--text-column", default="text", help="Text column (default: text)") parser.add_argument("--label-column", default="label", help="Label column (default: label, falls back to labels)") parser.add_argument("--train-split", default="train", help="Train split (default: train)") parser.add_argument("--eval-split", help="Eval split (default: validation, then test, then a held-out fraction of train)") parser.add_argument("--eval-fraction", type=float, default=0.1, help="Held-out fraction when no eval split exists (default: 0.1)") parser.add_argument("--max-samples", type=int, help="Cap train/eval examples (shuffled first)") parser.add_argument("--seed", type=int, default=42, help="Seed (default: 42)") parser.add_argument("--max-length", type=int, default=512, help="Max sequence length (default: 512; LFM2.5 encoders support 8192)") parser.add_argument("--epochs", type=int, default=3, help="Epochs (default: 3)") parser.add_argument("--lr", type=float, default=2e-5, help="Learning rate (default: 2e-5)") parser.add_argument("--batch-size", type=int, default=16, help="Batch size (default: 16)") parser.add_argument("--grad-accum", type=int, default=1, help="Gradient accumulation (default: 1)") parser.add_argument("--warmup-ratio", type=float, default=0.05, help="Warmup ratio (default: 0.05)") parser.add_argument("--gradient-checkpointing", action="store_true", help="Enable gradient checkpointing (for long contexts)") parser.add_argument("--no-bf16", action="store_true", help="Disable bf16 (train in fp32)") parser.add_argument("--private", action="store_true", help="Make output model repo private") parser.add_argument("--hf-token", help="HF token (or set HF_TOKEN)") args = parser.parse_args()
main( input_dataset=args.input_dataset, output_repo=args.output_repo, model_id=args.model, dataset_config=args.dataset_config, text_column=args.text_column, label_column=args.label_column, train_split=args.train_split, eval_split=args.eval_split, eval_fraction=args.eval_fraction, max_samples=args.max_samples, seed=args.seed, max_length=args.max_length, epochs=args.epochs, lr=args.lr, batch_size=args.batch_size, grad_accum=args.grad_accum, warmup_ratio=args.warmup_ratio, gradient_checkpointing=args.gradient_checkpointing, no_bf16=args.no_bf16, private=args.private, hf_token=args.hf_token, )README.md+66-2
train-classifier.pyAdded+814