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-base with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Tamarillo/zeroshot-policy-guard-base with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("zero-shot-classification", model="Tamarillo/zeroshot-policy-guard-base")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForSequenceClassification tokenizer = AutoTokenizer.from_pretrained("Tamarillo/zeroshot-policy-guard-base") model = AutoModelForSequenceClassification.from_pretrained("Tamarillo/zeroshot-policy-guard-base", device_map="auto") - Transformers.js
How to use Tamarillo/zeroshot-policy-guard-base 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-base'); - Notebooks
- Google Colab
- Kaggle
Release Tamarillo/zeroshot-policy-guard-base (Apache-2.0, ModernBERT/mmBERT zero-shot policy & NLI guard, FP32+FP16 ONNX 1.0000 parity, live llm-guard verified)
80554db verified Download scripts/eval_needle_ood.py from Tamarillo/zeroshot-policy-guard-base: direct link, hf CLI and curl.
- Browser
- Download file 6.91 kB
-
https://huggingface.co/Tamarillo/zeroshot-policy-guard-base/resolve/main/scripts/eval_needle_ood.py
- Command line
-
hf download hf://Tamarillo/zeroshot-policy-guard-base/scripts/eval_needle_ood.py
-
curl -L -o eval_needle_ood.py https://huggingface.co/Tamarillo/zeroshot-policy-guard-base/resolve/main/scripts/eval_needle_ood.py
6.91 kB
| """Unbiased, balanced OOD long-context needle diagnostics (zero Aegis taxonomy shortcut): | |
| 1. ood_ag_news_needle: 60 pos + 60 neg unseen AG News articles embedded in benign haystacks at 250/800/1600/3200 tok | |
| 2. ood_xnli_needle: 60 pos + 60 neg unseen XNLI EN premise/hypothesis pairs embedded in benign haystacks at 250/800/1600/3200 tok | |
| 3. aegis_clean_hyp: 60 unsafe + 60 safe Aegis-v2 test prompts at 250/800/1600/3200 tok using clean PolyGuard/general policy descriptions | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import random | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np | |
| import torch | |
| from datasets import load_dataset | |
| from sklearn.metrics import roc_auc_score | |
| from eval_suite import NLIAdapter | |
| GCS_OUT = "/mnt/disks/gcs/runs/tamarillo-lab-v3/outputs" | |
| MODELS = [ | |
| ("tamarillo-tiny-en", f"{GCS_OUT}/b1c53b1d9883/model"), | |
| ("tamarillo-small", f"{GCS_OUT}/682f8e1ba955/model"), | |
| ("tamarillo-base", f"{GCS_OUT}/ffd6c4a7c76f/model"), | |
| ("deberta-v3-base-zeroshot", "MoritzLaurer/deberta-v3-base-zeroshot-v2.0"), | |
| ("deberta-v3-large-zeroshot", "MoritzLaurer/deberta-v3-large-zeroshot-v2.0"), | |
| ("bge-m3-zeroshot", "MoritzLaurer/bge-m3-zeroshot-v2.0"), | |
| ("mdeberta-v3-mnli-xnli", "MoritzLaurer/mDeBERTa-v3-base-mnli-xnli"), | |
| ("modernbert-base-zeroshot", "MoritzLaurer/ModernBERT-base-zeroshot-v2.0"), | |
| ] | |
| # Completely neutral, distinct fillers (weather/nature/geology — zero overlap with AG News sports/business/sci-tech or XNLI) | |
| FILLERS = [ | |
| "Botanical field note: evergreen pine needles accumulate gradually along shaded northern slopes during late autumn.", | |
| "Geological survey entry: sedimentary sandstone formations exhibit horizontal bedding planes formed across shallow basins.", | |
| "Coastal tide log: morning low tide receded smoothly along the pebble shoreline under steady overcast skies.", | |
| "Gardening journal remark: perennial lavender shrubs tolerate dry gravel soils well when pruned after summer flowering.", | |
| "Forestry observation: moss colonies expand slowly across damp granite boulders near seasonal mountain streams.", | |
| "Orchard maintenance note: winter pruning opens interior canopy branches to improve spring sunlight penetration.", | |
| ] | |
| def _embed_depths(pos_pairs: list[tuple[str, str]], neg_pairs: list[tuple[str, str]], depths: list[int], seed: int) -> dict[int, list[tuple[str, str, int]]]: | |
| rng = random.Random(seed) | |
| by_d: dict[int, list[tuple[str, str, int]]] = {} | |
| for d in depths: | |
| items = [] | |
| for is_pos, plist in [(1, pos_pairs), (0, neg_pairs)]: | |
| for prem, hyp in plist: | |
| chunks, cur = [], 0 | |
| while cur < d: | |
| b = rng.choice(FILLERS) | |
| chunks.append(b) | |
| cur += len(b) + 2 | |
| doc = "\n\n".join(chunks) + "\n\n" + prem + "\n\n" + rng.choice(FILLERS) | |
| items.append((doc, hyp, is_pos)) | |
| by_d[d // 4] = items | |
| return by_d | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| 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 | |
| depths = [1000, 3200, 6400, 12800] | |
| # Suite 1: OOD AG News long-context topic needle (60 pos + 60 neg) | |
| ds_ag = list(load_dataset("fancyzhx/ag_news", split="test")) | |
| rng1 = random.Random(101) | |
| rng1.shuffle(ds_ag) | |
| ag_labels = ["world news", "sports", "business and finance", "science and technology"] | |
| ag_pos, ag_neg = [], [] | |
| for row in ds_ag[:60]: | |
| txt = (row["text"] or "").strip() | |
| g = int(row["label"]) | |
| ag_pos.append((txt, f"This text is about {ag_labels[g]}.")) | |
| wrong = rng1.choice([i for i in range(4) if i != g]) | |
| ag_neg.append((txt, f"This text is about {ag_labels[wrong]}.")) | |
| ag_by_d = _embed_depths(ag_pos, ag_neg, depths, seed=102) | |
| # Suite 2: OOD XNLI EN long-context entailment needle (60 pos + 60 neg) | |
| ds_xn = list(load_dataset("facebook/xnli", "en", split="test", trust_remote_code=True)) | |
| rng2 = random.Random(201) | |
| rng2.shuffle(ds_xn) | |
| xn_pos, xn_neg = [], [] | |
| for row in ds_xn: | |
| p, h = (row["premise"] or "").strip(), (row["hypothesis"] or "").strip() | |
| lbl = int(row["label"]) | |
| if lbl == 0 and len(xn_pos) < 60: | |
| xn_pos.append((p, h)) | |
| elif lbl in (1, 2) and len(xn_neg) < 60: | |
| xn_neg.append((p, h)) | |
| if len(xn_pos) >= 60 and len(xn_neg) >= 60: | |
| break | |
| xn_by_d = _embed_depths(xn_pos, xn_neg, depths, seed=202) | |
| # Suite 3: Aegis-v2 safe vs unsafe using clean general policy hypothesis ("This text involves harmful or illegal activity.") | |
| ds_ae = load_dataset("nvidia/Aegis-AI-Content-Safety-Dataset-2.0", split="test") | |
| ae_pos, ae_neg = [], [] | |
| for row in ds_ae: | |
| p = (row.get("prompt") or "").strip() | |
| pl = (row.get("prompt_label") or "").strip().lower() | |
| if len(p) < 15: | |
| continue | |
| if pl == "unsafe" and len(ae_pos) < 60: | |
| ae_pos.append((p, "This text involves violence, illegal activity, or harmful content.")) | |
| elif pl == "safe" and len(ae_neg) < 60: | |
| ae_neg.append((p, "This text involves violence, illegal activity, or harmful content.")) | |
| if len(ae_pos) >= 60 and len(ae_neg) >= 60: | |
| break | |
| ae_by_d = _embed_depths(ae_pos, ae_neg, depths, seed=302) | |
| all_suites = { | |
| "ood_ag_news_needle": ag_by_d, | |
| "ood_xnli_needle": xn_by_d, | |
| "aegis_clean_hyp_needle": ae_by_d, | |
| } | |
| out: dict[str, Any] = {"models": {}} | |
| for name, src in MODELS: | |
| print(f"[needle_ood] Evaluating {name} ...") | |
| ad = NLIAdapter(name, src) | |
| m_res: dict[str, Any] = {"native_max_length": ad.native_max_len, "suites": {}} | |
| for sname, by_d in all_suites.items(): | |
| s_res = {} | |
| for tok_d, items in by_d.items(): | |
| prems = [x[0] for x in items] | |
| hyps = [x[1] for x in items] | |
| y = np.array([x[2] for x in items]) | |
| p_ent = ad.entailment_probs(prems, hyps, batch_size=16, max_length=4096) | |
| pos_m, neg_m = (y == 1), (y == 0) | |
| s_res[f"depth_{tok_d}_tok"] = { | |
| "recall": round(float((p_ent[pos_m] >= 0.5).mean()), 4), | |
| "fpr": round(float((p_ent[neg_m] >= 0.5).mean()), 4), | |
| "roc_auc": round(float(roc_auc_score(y, p_ent)), 4), | |
| } | |
| m_res["suites"][sname] = s_res | |
| out["models"][name] = m_res | |
| ad.close() | |
| Path(args.out_json).write_text(json.dumps(out, indent=2), encoding="utf-8") | |
| print("[needle_ood] DONE!") | |
| if __name__ == "__main__": | |
| main() | |