Text Classification
Transformers
Safetensors
English
modernbert
multi-head-classification
llm-routing
llm-gateway
model-routing
prompt-classification
query-classification
data-classification
retrieval-augmented-generation
calibration
synthetic-data
Instructions to use s-ttp/aiva-rlcd-modernbert with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use s-ttp/aiva-rlcd-modernbert with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="s-ttp/aiva-rlcd-modernbert")# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("s-ttp/aiva-rlcd-modernbert", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download training/train.py from s-ttp/aiva-rlcd-modernbert: direct link, hf CLI and curl.
- Browser
- Download file 15.3 kB
-
https://huggingface.co/s-ttp/aiva-rlcd-modernbert/resolve/main/training/train.py
- Command line
-
hf download hf://s-ttp/aiva-rlcd-modernbert/training/train.py
-
curl -L -o train.py https://huggingface.co/s-ttp/aiva-rlcd-modernbert/resolve/main/training/train.py
15.3 kB
| # Copyright 2026 The AiVa proof-of-concept team. Licensed under the Apache License, Version 2.0. | |
| """Train an RLCD classifier: one ModernBERT encoder, one linear head per output, then one temperature per head. | |
| python train.py --data data/ --taxonomy taxonomy.json --out rlcd-mine \ | |
| --balance-sensitivity 0.5 --bucket-by-length \ | |
| --prior public=0.146,internal=0.527,confidential=0.297,restricted=0.024,sovereign-only=0.006 | |
| `--data` holds train.jsonl, validation.jsonl and test.jsonl. Each row has "text" (or "messages", rendered | |
| as `[role] content` lines) and one field per head; a row may leave a head out. The defaults are the recipe of | |
| the published model: ModernBERT-base at a pinned revision, 3 epochs, AdamW, learning rate 5e-5 with a cosine | |
| schedule and 6% warm-up, batch 32, 1,024 tokens, the sum of the heads' cross-entropies. | |
| - `--init-from` starts from an RLCD checkpoint (a folder or a Hub repo such as s-ttp/aiva-rlcd-modernbert) | |
| instead of ModernBERT-base: heads whose classes are unchanged keep their weights, the others start fresh. | |
| The default learning rate is then 2e-5. The encoder still moves, so a head your rows never label gets no | |
| training signal and can drift: label every head where you can, and score the unchanged heads on held-out | |
| rows before you ship. | |
| - `--balance-sensitivity A` samples rows with weight count(level)^-A (0.5 is square-root balancing), so rare | |
| levels are seen more often. | |
| - `--bucket-by-length` batches rows of similar length: long pastes would otherwise pad most batches. | |
| - `--prior` fits the temperatures on validation rows weighted to your production sensitivity mix. | |
| The output folder loads with `rlcd.RlcdClassifier` and the model card's loader. | |
| """ | |
| import argparse | |
| import itertools | |
| import json | |
| import math | |
| import time | |
| from pathlib import Path | |
| import torch | |
| from huggingface_hub import snapshot_download | |
| from safetensors.torch import load_file, save_file | |
| from torch import nn | |
| from transformers import AutoConfig, AutoModel, AutoTokenizer, get_cosine_schedule_with_warmup | |
| from rlcd import pool, render | |
| class MultiHead(nn.Module): | |
| def __init__(self, encoder: nn.Module, heads: dict[str, list[str]], dropout: float = 0.1) -> None: | |
| super().__init__() | |
| self.encoder = encoder | |
| self.dropout = nn.Dropout(dropout) | |
| hidden = encoder.config.hidden_size | |
| self.heads = nn.ModuleDict({name: nn.Linear(hidden, len(classes)) for name, classes in heads.items()}) | |
| def forward(self, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> dict[str, torch.Tensor]: | |
| hidden = self.encoder(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state | |
| pooled = self.dropout(pool(hidden, attention_mask)) | |
| return {name: head(pooled) for name, head in self.heads.items()} | |
| def read_split(path: Path) -> list[dict]: | |
| rows = [json.loads(line) for line in path.read_text().splitlines() if line.strip()] | |
| for row in rows: | |
| row.setdefault("text", render(row["messages"]) if "messages" in row else None) | |
| return rows | |
| def fit_temperature(logits: torch.Tensor, labels: torch.Tensor, weights: torch.Tensor | None = None) -> float: | |
| log_t = torch.zeros(1, requires_grad=True) | |
| optimiser = torch.optim.LBFGS([log_t], lr=0.1, max_iter=200) | |
| w = torch.ones(len(labels)) if weights is None else weights | |
| def closure() -> torch.Tensor: | |
| optimiser.zero_grad() | |
| loss = (nn.functional.cross_entropy(logits / log_t.exp(), labels, reduction="none") * w).sum() / w.sum() | |
| loss.backward() | |
| return loss | |
| optimiser.step(closure) | |
| return log_t.exp().item() | |
| def ece(probs: torch.Tensor, labels: torch.Tensor, bins: int = 15) -> float: | |
| confidence, prediction = probs.max(dim=1) | |
| correct, total = prediction.eq(labels).float(), 0.0 | |
| for low, high in itertools.pairwise(torch.linspace(0, 1, bins + 1)): | |
| in_bin = (confidence > low) & (confidence <= high) | |
| if in_bin.any(): | |
| total += in_bin.float().mean().item() * abs(confidence[in_bin].mean() - correct[in_bin].mean()).item() | |
| return total | |
| def macro_f1(labels: torch.Tensor, prediction: torch.Tensor, classes: int) -> float: | |
| scores = [] # over every class, as the published figures (a class absent from the split scores 0) | |
| for c in range(classes): | |
| tp = ((prediction == c) & (labels == c)).sum().item() | |
| fp, fn = ((prediction == c) & (labels != c)).sum().item(), ((prediction != c) & (labels == c)).sum().item() | |
| scores.append(0.0 if tp == 0 else 2 * tp / (2 * tp + fp + fn)) | |
| return sum(scores) / classes | |
| def buckets(lengths: list[int], batch_size: int, weights: torch.Tensor | None, generator: torch.Generator, | |
| pool_batches: int = 50) -> list[list[int]]: | |
| """One epoch of batches of similar length (rows drawn with replacement when weighted).""" | |
| n, chunk = len(lengths), batch_size * pool_batches | |
| order = (torch.randperm(n, generator=generator) if weights is None | |
| else torch.multinomial(weights, n, replacement=True, generator=generator)).tolist() | |
| batches = [] | |
| for i in range(0, n, chunk): | |
| part = sorted(order[i : i + chunk], key=lengths.__getitem__) | |
| batches += [part[k : k + batch_size] for k in range(0, len(part), batch_size)] | |
| return [batches[j] for j in torch.randperm(len(batches), generator=generator).tolist()] | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument("--data", type=Path, required=True) | |
| parser.add_argument("--taxonomy", type=Path, default=Path(__file__).with_name("taxonomy.json")) | |
| parser.add_argument("--out", type=Path, required=True) | |
| parser.add_argument("--base-model", default="answerdotai/ModernBERT-base") | |
| parser.add_argument("--base-revision", default="8949b909ec900327062f0ebf497f51aef5e6f0c8", | |
| help="the published model's ModernBERT-base revision") | |
| parser.add_argument("--init-from", default=None, help="an RLCD folder or Hub repo to continue from") | |
| parser.add_argument("--max-length", type=int, default=1024) | |
| parser.add_argument("--epochs", type=float, default=3.0) | |
| parser.add_argument("--learning-rate", type=float, default=None, help="default 5e-5, or 2e-5 with --init-from") | |
| parser.add_argument("--batch-size", type=int, default=32) | |
| parser.add_argument("--balance-sensitivity", type=float, default=0.0) | |
| parser.add_argument("--bucket-by-length", action="store_true") | |
| parser.add_argument("--prior", default=None, help="level=share,... for the temperature fit") | |
| parser.add_argument("--seed", type=int, default=13) | |
| args = parser.parse_args() | |
| torch.manual_seed(args.seed) | |
| if args.learning_rate is None: | |
| args.learning_rate = 2e-5 if args.init_from else 5e-5 | |
| heads = {name: list(classes) for name, classes in json.loads(args.taxonomy.read_text())["heads"].items()} | |
| splits = {s: read_split(args.data / f"{s}.jsonl") for s in ("train", "validation", "test")} | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| init = None | |
| if args.init_from: | |
| init = Path(args.init_from) if Path(args.init_from).is_dir() else Path(snapshot_download(args.init_from)) | |
| tokenizer = AutoTokenizer.from_pretrained(init) | |
| encoder = AutoModel.from_config(AutoConfig.from_pretrained(init / "encoder")) | |
| else: | |
| tokenizer = AutoTokenizer.from_pretrained(args.base_model, revision=args.base_revision) | |
| encoder = AutoModel.from_pretrained(args.base_model, revision=args.base_revision, dtype=torch.float32) | |
| model = MultiHead(encoder, heads) | |
| if init: | |
| old = json.loads((init / "rlcd_config.json").read_text()) | |
| state = load_file(str(init / "model.safetensors")) | |
| keep = {k: v for k, v in state.items() if k.startswith("encoder.") or ( | |
| k.split(".")[1] in heads and old["heads"].get(k.split(".")[1]) == heads[k.split(".")[1]])} | |
| missing, unexpected = model.load_state_dict(keep, strict=False) | |
| fresh = [h for h in heads if old["heads"].get(h) != heads[h]] | |
| assert not unexpected and all(k.split(".")[1] in fresh for k in missing), (missing, unexpected) | |
| print(json.dumps({"init_from": args.init_from, "fresh_heads": fresh}), flush=True) | |
| model.to(device) | |
| index = {name: {label: i for i, label in enumerate(classes)} for name, classes in heads.items()} | |
| def encode(rows: list[dict]) -> list[dict]: | |
| ids = tokenizer([r["text"] for r in rows], truncation=True, max_length=args.max_length)["input_ids"] | |
| return [{"input_ids": i, **{h: index[h].get(r.get(h), -100) for h in heads}} for i, r in zip(ids, rows, strict=True)] | |
| data = {s: encode(rows) for s, rows in splits.items()} | |
| for h in heads: | |
| if not any(r[h] != -100 for r in data["train"]): | |
| print(f"warning: no training row labels {h}; it gets no training signal and can drift", flush=True) | |
| pad = tokenizer.pad_token_id or 0 | |
| def collate(rows: list[dict]) -> dict[str, torch.Tensor]: | |
| length = max(len(r["input_ids"]) for r in rows) | |
| ids = torch.tensor([r["input_ids"] + [pad] * (length - len(r["input_ids"])) for r in rows]) | |
| mask = torch.tensor([[1] * len(r["input_ids"]) + [0] * (length - len(r["input_ids"])) for r in rows]) | |
| return {"input_ids": ids, "attention_mask": mask, **{h: torch.tensor([r[h] for r in rows]) for h in heads}} | |
| train = data["train"] | |
| weights = None | |
| if args.balance_sensitivity and "sensitivity" in heads: | |
| levels = [r["sensitivity"] for r in train] | |
| seen = {lvl: levels.count(lvl) for lvl in set(levels)} | |
| weights = torch.tensor([seen[lvl] ** -args.balance_sensitivity for lvl in levels], dtype=torch.double) | |
| generator = torch.Generator().manual_seed(args.seed) | |
| def epoch() -> list[list[int]]: | |
| if args.bucket_by_length: | |
| return buckets([len(r["input_ids"]) for r in train], args.batch_size, weights, generator) | |
| order = (torch.randperm(len(train), generator=generator) if weights is None else | |
| torch.multinomial(weights, len(train), replacement=True, generator=generator)).tolist() | |
| return [order[i : i + args.batch_size] for i in range(0, len(order), args.batch_size)] | |
| steps = math.ceil(len(epoch()) * args.epochs) | |
| optimiser = torch.optim.AdamW(model.parameters(), lr=args.learning_rate, weight_decay=0.01) | |
| scheduler = get_cosine_schedule_with_warmup(optimiser, int(0.06 * steps), steps) | |
| autocast = torch.autocast(device_type=device, dtype=torch.bfloat16, enabled=device == "cuda") | |
| started, step = time.time(), 0 | |
| model.train() | |
| while step < steps: | |
| for batch_ids in epoch(): | |
| batch = collate([train[i] for i in batch_ids]) | |
| with autocast: | |
| outputs = model(batch["input_ids"].to(device), batch["attention_mask"].to(device)) | |
| loss = sum(nn.functional.cross_entropy(outputs[h].float(), batch[h].to(device), ignore_index=-100) | |
| for h in heads if (batch[h] != -100).any()) | |
| loss.backward() | |
| torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) | |
| optimiser.step() | |
| scheduler.step() | |
| optimiser.zero_grad() | |
| step += 1 | |
| if step % 50 == 0 or step == steps: | |
| print(json.dumps({"step": step, "steps": steps, "loss": round(loss.item(), 4), | |
| "elapsed_s": round(time.time() - started)}), flush=True) | |
| if step >= steps: | |
| break | |
| def logits_for(split: str) -> dict[str, tuple[torch.Tensor, torch.Tensor]]: | |
| model.eval() | |
| collected: dict[str, list] = {h: [] for h in heads} | |
| rows = data[split] | |
| for i in range(0, len(rows), args.batch_size * 2): | |
| batch = collate(rows[i : i + args.batch_size * 2]) | |
| with autocast: | |
| outputs = model(batch["input_ids"].to(device), batch["attention_mask"].to(device)) | |
| for h in heads: | |
| collected[h].append((outputs[h].float().cpu(), batch[h])) | |
| result = {} | |
| for h in heads: | |
| logits = torch.cat([lg for lg, _ in collected[h]]) | |
| labels = torch.cat([lb for _, lb in collected[h]]) | |
| result[h] = (logits[labels != -100], labels[labels != -100]) | |
| return result | |
| validation, test = logits_for("validation"), logits_for("test") | |
| temperatures, report = {}, {} | |
| for h, classes in heads.items(): | |
| logits, labels = validation[h] | |
| weights_v = None | |
| if args.prior and len(labels): # weight validation rows to the production sensitivity mix | |
| prior = {k: float(v) for k, v in (item.split("=") for item in args.prior.split(","))} | |
| levels = [splits["validation"][i].get("sensitivity") for i in range(len(splits["validation"])) | |
| if splits["validation"][i].get(h) in index[h]] | |
| share = {lvl: levels.count(lvl) / len(levels) for lvl in set(levels)} | |
| if all(lvl in prior for lvl in levels): | |
| weights_v = torch.tensor([prior[lvl] / share[lvl] for lvl in levels], dtype=torch.float32) | |
| temperatures[h] = fit_temperature(logits, labels, weights_v) if len(labels) else 1.0 | |
| if len(labels) < 200: | |
| print(f"warning: {h} has {len(labels)} validation rows; its temperature is unreliable", flush=True) | |
| if not (math.isfinite(temperatures[h]) and 0.05 <= temperatures[h] <= 20): | |
| print(f"warning: {h} temperature {temperatures[h]} is implausible; using 1.0", flush=True) | |
| temperatures[h] = 1.0 | |
| logits, labels = test[h] | |
| if not len(labels): | |
| continue | |
| before, after = logits.softmax(-1), (logits / temperatures[h]).softmax(-1) | |
| prediction = before.argmax(-1) | |
| report[h] = {"test_rows": len(labels), "accuracy": round(prediction.eq(labels).float().mean().item(), 4), | |
| "macro_f1": round(macro_f1(labels, prediction, len(classes)), 4), | |
| "ece_before": round(ece(before, labels), 4), "ece_after": round(ece(after, labels), 4), | |
| "temperature": round(temperatures[h], 4), "provenance": "measured"} | |
| print(json.dumps({"test_report": report}, indent=1), flush=True) | |
| out = args.out | |
| out.mkdir(parents=True, exist_ok=True) | |
| save_file({k: v.contiguous().cpu() for k, v in model.state_dict().items()}, str(out / "model.safetensors")) | |
| tokenizer.save_pretrained(out) | |
| encoder.config.save_pretrained(out / "encoder") | |
| config = { | |
| "architecture": "aiva-rlcd-multihead", "base_model": args.init_from or f"{args.base_model}@{args.base_revision}", | |
| "pooling": "mean", "max_length": args.max_length, "heads": heads, "temperatures": temperatures, | |
| "input_format": "messages joined as '[role] content' lines", | |
| "hyperparameters": {k: str(v) for k, v in vars(args).items()}, | |
| "train_seconds": round(time.time() - started), "test_report": report, | |
| } | |
| (out / "rlcd_config.json").write_text(json.dumps(config, indent=2)) | |
| print(f"saved {out}", flush=True) | |
| if __name__ == "__main__": | |
| main() | |