Zero-Shot Classification
Transformers
ONNX
Safetensors
Transformers.js
modernbert
text-classification
nli
guardrails
llm-guard
ban-topics
policy-enforcement
tamarillo
zero-shot
litellm
nemo-guardrails
open-webui
topic-classification
Instructions to use Tamarillo/zeroshot-policy-guard-small with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Tamarillo/zeroshot-policy-guard-small with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("zero-shot-classification", model="Tamarillo/zeroshot-policy-guard-small")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForSequenceClassification tokenizer = AutoTokenizer.from_pretrained("Tamarillo/zeroshot-policy-guard-small") model = AutoModelForSequenceClassification.from_pretrained("Tamarillo/zeroshot-policy-guard-small", device_map="auto") - Transformers.js
How to use Tamarillo/zeroshot-policy-guard-small with Transformers.js:
// npm i @huggingface/transformers import { pipeline } from '@huggingface/transformers'; // Allocate pipeline const pipe = await pipeline('zero-shot-classification', 'Tamarillo/zeroshot-policy-guard-small'); - Notebooks
- Google Colab
- Kaggle
Release Tamarillo/zeroshot-policy-guard-small (Apache-2.0, ModernBERT/mmBERT zero-shot policy & NLI guard, FP32+FP16 ONNX 1.0000 parity, live llm-guard verified)
3af76b6 verified Download scripts/eval_suite.py from Tamarillo/zeroshot-policy-guard-small: direct link, hf CLI and curl.
- Browser
- Download file 12.9 kB
-
https://huggingface.co/Tamarillo/zeroshot-policy-guard-small/resolve/main/scripts/eval_suite.py
- Command line
-
hf download hf://Tamarillo/zeroshot-policy-guard-small/scripts/eval_suite.py
-
curl -L -o eval_suite.py https://huggingface.co/Tamarillo/zeroshot-policy-guard-small/resolve/main/scripts/eval_suite.py
12.9 kB
| """Unified apples-to-apples evaluation suite for Tamarillo zeroshot-policy-guard and 5 legacy/8K baselines. | |
| Evaluates: | |
| - Strictly Zero-Shot OOD Multilingual NLI: facebook/xnli (15 languages, macro F1 & ROC-AUC, non-EN breakdown) | |
| - Strictly Zero-Shot OOD Topic Classification: fancyzhx/ag_news (4-way macro F1 / accuracy) | |
| - Strictly Zero-Shot OOD Financial Intent: PolyAI/banking77 (10-way candidate accuracy / macro F1) | |
| - Strictly Zero-Shot OOD Real Long-Document Legal NLI: kiddothe2b/contract-nli (macro F1 & ROC-AUC) | |
| - Unconfounded Long-Context Late-Policy Needle Recall (exact same 60 needles at ~250 / 800 / 1,600 / 3,200 tok) | |
| - L4 GPU p50/p95 latency (n=30) at 64 and 2,048 tokens | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import gc | |
| import json | |
| import os | |
| import statistics | |
| import time | |
| from collections import defaultdict | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np | |
| import torch | |
| from sklearn.metrics import accuracy_score, f1_score, roc_auc_score | |
| from transformers import AutoModelForSequenceClassification, AutoTokenizer | |
| BENIGN_FILLER = ( | |
| "Enterprise operational log summary: all regional clusters passed routine health probes with " | |
| "99.98% availability, normal memory pressure, and zero unresolved infrastructure incidents. " | |
| ) | |
| def load_jsonl(path: Path) -> list[dict[str, Any]]: | |
| if not path.exists(): | |
| return [] | |
| with path.open("r", encoding="utf-8") as f: | |
| return [json.loads(ln) for ln in f if ln.strip()] | |
| def _softmax(x: np.ndarray) -> np.ndarray: | |
| x32 = x.astype(np.float32) | |
| e = np.exp(x32 - np.max(x32, axis=-1, keepdims=True)) | |
| return e / np.sum(e, axis=-1, keepdims=True) | |
| class NLIAdapter: | |
| """Supports both 2-class (entailment/not_entailment) and 3-class (entailment/neutral/contradiction) NLI models.""" | |
| def __init__(self, name: str, path_or_id: str, max_length_override: int | None = None) -> None: | |
| self.name = name | |
| self.path_or_id = path_or_id | |
| self.device = "cuda" if torch.cuda.is_available() else "cpu" | |
| self.tokenizer = AutoTokenizer.from_pretrained(path_or_id, use_fast=True) | |
| self.model = AutoModelForSequenceClassification.from_pretrained(path_or_id) | |
| if hasattr(self.model.config, "reference_compile"): | |
| self.model.config.reference_compile = False | |
| self.model.to(self.device).eval() | |
| cfg = self.model.config | |
| self.id2label = {int(k): str(v).lower() for k, v in (cfg.id2label or {}).items()} | |
| self.ent_idx = next((k for k, v in self.id2label.items() if v == "entailment"), 0) | |
| self.con_idx = next((k for k, v in self.id2label.items() if "contradict" in v or "not_entail" in v), 1) | |
| self.num_labels = int(cfg.num_labels) | |
| mpe = int(getattr(cfg, "max_position_embeddings", 512) or 512) | |
| if mpe in (512, 514): | |
| self.native_max_len = 512 | |
| else: | |
| self.native_max_len = min(max_length_override or 4096, mpe) | |
| self.param_count = sum(p.numel() for p in self.model.parameters()) | |
| self.is_deberta = "deberta" in str(getattr(cfg, "model_type", "")).lower() | |
| def entailment_probs(self, premises: list[str], hypotheses: list[str], batch_size: int = 32, max_length: int | None = None) -> np.ndarray: | |
| ml = min(max_length or self.native_max_len, self.native_max_len) | |
| use_amp = self.device == "cuda" and not self.is_deberta | |
| dtype = torch.bfloat16 if (self.device == "cuda" and torch.cuda.is_bf16_supported()) else torch.float16 | |
| out = [] | |
| for i in range(0, len(premises), batch_size): | |
| enc = self.tokenizer( | |
| premises[i : i + batch_size], | |
| hypotheses[i : i + batch_size], | |
| padding=True, | |
| truncation="only_first", | |
| max_length=ml, | |
| return_token_type_ids=False, | |
| return_tensors="pt", | |
| ) | |
| enc = {k: v.to(self.device) for k, v in enc.items()} | |
| with torch.no_grad(): | |
| if use_amp: | |
| with torch.amp.autocast("cuda", dtype=dtype): | |
| logits = self.model(**enc).logits.float().cpu().numpy() | |
| else: | |
| logits = self.model(**enc).logits.float().cpu().numpy() | |
| if self.num_labels == 2: | |
| p_ent = _softmax(logits)[:, self.ent_idx] | |
| else: | |
| # Standard HF zero-shot-classification convention for 3-class NLI: softmax over [entailment, contradiction] | |
| # For binary NLI (entailment vs neutral+contradiction), full 3-way softmax[:, ent_idx] is exact! | |
| p_ent = _softmax(logits)[:, self.ent_idx] | |
| out.append(p_ent) | |
| return np.concatenate(out, axis=0) if out else np.zeros((0,), dtype=np.float32) | |
| def zero_shot_score_candidates(self, text: str, candidates: list[str], template: str = "This example is {}.") -> np.ndarray: | |
| prems = [text] * len(candidates) | |
| hyps = [template.format(c) for c in candidates] | |
| return self.entailment_probs(prems, hyps, batch_size=len(candidates)) | |
| def bench_gpu_latency(self, seq_len: int, n_runs: int = 30) -> dict[str, Any] | None: | |
| if self.device != "cuda": | |
| return None | |
| eff = min(seq_len, self.native_max_len) | |
| txt = (BENIGN_FILLER * 90) if eff >= 512 else (BENIGN_FILLER * 4) | |
| enc = self.tokenizer(txt, "This example is infrastructure monitoring.", truncation="only_first", padding="max_length", max_length=eff, return_token_type_ids=False, return_tensors="pt") | |
| enc = {k: v.to(self.device) for k, v in enc.items()} | |
| use_amp = not self.is_deberta | |
| dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16 | |
| with torch.no_grad(): | |
| for _ in range(8): | |
| if use_amp: | |
| with torch.amp.autocast("cuda", dtype=dtype): | |
| _ = self.model(**enc) | |
| else: | |
| _ = self.model(**enc) | |
| torch.cuda.synchronize() | |
| times = [] | |
| for _ in range(n_runs): | |
| t0 = time.perf_counter() | |
| if use_amp: | |
| with torch.amp.autocast("cuda", dtype=dtype): | |
| _ = self.model(**enc) | |
| else: | |
| _ = self.model(**enc) | |
| torch.cuda.synchronize() | |
| times.append((time.perf_counter() - t0) * 1000.0) | |
| times.sort() | |
| return { | |
| "requested_seq_len": seq_len, | |
| "effective_seq_len": eff, | |
| "p50_ms": round(statistics.median(times), 2), | |
| "p95_ms": round(times[int(0.95 * (len(times) - 1))], 2), | |
| "gpu_name": torch.cuda.get_device_name(0), | |
| } | |
| def close(self) -> None: | |
| del self.model | |
| gc.collect() | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() | |
| def eval_model(adapter: NLIAdapter, suites: dict[str, list[dict[str, Any]]]) -> dict[str, Any]: | |
| out: dict[str, Any] = {"params_m": round(adapter.param_count / 1e6, 2), "native_max_length": adapter.native_max_len, "suites": {}} | |
| # 1. Zero-shot OOD XNLI (15 languages) | |
| if suites.get("ood_xnli"): | |
| rows = suites["ood_xnli"] | |
| p_ent = adapter.entailment_probs([r["premise"] for r in rows], [r["hypothesis"] for r in rows], batch_size=32) | |
| y_ent = np.array([1 if int(r["label"]) == 0 else 0 for r in rows]) | |
| by_lang = defaultdict(list) | |
| for i, r in enumerate(rows): | |
| by_lang[r["language"]].append(i) | |
| lang_aucs, lang_f1s, ne_aucs, ne_f1s = [], [], [], [] | |
| per_lang = {} | |
| for l, idxs in sorted(by_lang.items()): | |
| ia = np.array(idxs) | |
| auc = float(roc_auc_score(y_ent[ia], p_ent[ia])) if len(np.unique(y_ent[ia])) == 2 else 0.0 | |
| f1 = float(f1_score(y_ent[ia], (p_ent[ia] >= 0.5).astype(int), zero_division=0)) | |
| per_lang[l] = {"roc_auc": round(auc, 4), "ent_f1": round(f1, 4), "n": len(idxs)} | |
| lang_aucs.append(auc) | |
| lang_f1s.append(f1) | |
| if l != "en": | |
| ne_aucs.append(auc) | |
| ne_f1s.append(f1) | |
| out["suites"]["ood_xnli"] = { | |
| "n": len(rows), | |
| "overall_roc_auc": round(float(roc_auc_score(y_ent, p_ent)), 4), | |
| "overall_ent_f1": round(float(f1_score(y_ent, (p_ent >= 0.5).astype(int), zero_division=0)), 4), | |
| "macro_lang_roc_auc": round(float(np.mean(lang_aucs)), 4), | |
| "non_en_macro_roc_auc": round(float(np.mean(ne_aucs)), 4) if ne_aucs else None, | |
| "non_en_macro_f1": round(float(np.mean(ne_f1s)), 4) if ne_f1s else None, | |
| "per_language": per_lang, | |
| } | |
| # 2. Zero-shot OOD AG News (4-class topic classification) & Banking77 (10-way intent) | |
| for sname in ("ood_ag_news", "ood_banking77"): | |
| if suites.get(sname): | |
| rows = suites[sname] | |
| prems, hyps, offsets = [], [], [] | |
| for r in rows: | |
| cands = r["candidate_labels"] | |
| offsets.append((len(prems), len(prems) + len(cands))) | |
| for c in cands: | |
| prems.append(r["text"]) | |
| hyps.append(f"This text is about {c}.") | |
| scores = adapter.entailment_probs(prems, hyps, batch_size=64) | |
| preds = [int(np.argmax(scores[a:b])) for a, b in offsets] | |
| golds = [int(r["gold_idx"]) for r in rows] | |
| out["suites"][sname] = { | |
| "n": len(rows), | |
| "accuracy": round(float(accuracy_score(golds, preds)), 4), | |
| "macro_f1": round(float(f1_score(golds, preds, average="macro", zero_division=0)), 4), | |
| } | |
| # 3. Zero-shot OOD ContractNLI (real long-document legal NDA entailment!) | |
| if suites.get("ood_contract_nli"): | |
| rows = suites["ood_contract_nli"] | |
| p_ent = adapter.entailment_probs([r["premise"] for r in rows], [r["hypothesis"] for r in rows], batch_size=8, max_length=4096) | |
| y_ent = np.array([1 if int(r["label"]) == 0 else 0 for r in rows]) | |
| pred = (p_ent >= 0.5).astype(int) | |
| out["suites"]["ood_contract_nli"] = { | |
| "n": len(rows), | |
| "roc_auc": round(float(roc_auc_score(y_ent, p_ent)), 4) if len(np.unique(y_ent)) == 2 else None, | |
| "ent_f1": round(float(f1_score(y_ent, pred, zero_division=0)), 4), | |
| "macro_f1": round(float(f1_score(y_ent, pred, average="macro", zero_division=0)), 4), | |
| } | |
| # 4. Unconfounded Long-Context Late-Policy Needle Recall (exact same 60 needles at all 4 depths!) | |
| if suites.get("long_context_needle"): | |
| rows = suites["long_context_needle"] | |
| p_ent = adapter.entailment_probs([r["premise"] for r in rows], [r["hypothesis"] for r in rows], batch_size=16, max_length=4096) | |
| by_d = defaultdict(list) | |
| for i, r in enumerate(rows): | |
| by_d[int(r.get("approx_token_depth", 0))].append(i) | |
| out["suites"]["long_context_needle"] = { | |
| f"depth_{d}_tok": {"entailment_recall": round(float((p_ent[np.array(idxs)] >= 0.5).mean()), 4), "n": len(idxs)} | |
| for d, idxs in sorted(by_d.items()) | |
| } | |
| out["gpu_latency_64"] = adapter.bench_gpu_latency(64, n_runs=30) | |
| out["gpu_latency_2048"] = adapter.bench_gpu_latency(2048, n_runs=30) | |
| return out | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--data-dir", type=str, required=True) | |
| parser.add_argument("--models", nargs="+", required=True) | |
| parser.add_argument("--out-json", type=str, required=True) | |
| args = parser.parse_args() | |
| os.environ.setdefault("HF_HOME", "/tmp/hf") | |
| os.environ["TORCH_COMPILE_DISABLE"] = "1" | |
| if hasattr(torch, "_dynamo"): | |
| torch._dynamo.config.disable = True | |
| data_dir = Path(args.data_dir) | |
| suites = {s: load_jsonl(data_dir / f"test_{s}.jsonl") for s in ("ood_xnli", "ood_ag_news", "ood_banking77", "ood_contract_nli", "long_context_needle")} | |
| results: dict[str, Any] = {"models": {}} | |
| for spec in args.models: | |
| name, path_or_id = spec.split("=", 1) | |
| print(f"\n[eval] === Evaluating {name} ({path_or_id}) ===") | |
| t0 = time.time() | |
| try: | |
| ad = NLIAdapter(name, path_or_id) | |
| results["models"][name] = eval_model(ad, suites) | |
| results["models"][name]["source"] = path_or_id | |
| results["models"][name]["eval_sec"] = round(time.time() - t0, 1) | |
| ad.close() | |
| except Exception as e: | |
| print(f"[eval][ERROR] {name}: {e}") | |
| results["models"][name] = {"error": repr(e), "source": path_or_id} | |
| Path(args.out_json).write_text(json.dumps(results, indent=2), encoding="utf-8") | |
| print(f"[eval] Saved report -> {args.out_json}") | |
| if __name__ == "__main__": | |
| main() | |