Instructions to use Tamarillo/toxicity-safety-guard-base with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Tamarillo/toxicity-safety-guard-base with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="Tamarillo/toxicity-safety-guard-base")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForSequenceClassification tokenizer = AutoTokenizer.from_pretrained("Tamarillo/toxicity-safety-guard-base") model = AutoModelForSequenceClassification.from_pretrained("Tamarillo/toxicity-safety-guard-base", device_map="auto") - Transformers.js
How to use Tamarillo/toxicity-safety-guard-base with Transformers.js:
// npm i @huggingface/transformers import { pipeline } from '@huggingface/transformers'; // Allocate pipeline const pipe = await pipeline('text-classification', 'Tamarillo/toxicity-safety-guard-base'); - Notebooks
- Google Colab
- Kaggle
Tamarillo/toxicity-safety-guard-base
A commercially clean (Apache-2.0), zero-trust_remote_code, long-context multi-label toxicity and AI content safety classifier built on jhu-clsp/mmBERT-base (307.5M parameters, 8,192 backbone context window, fine-tuned and validated up to 3,584 tokens) with native [CLS] global-attention pooling and parity-verified ONNX exports.
- Languages: 17+ languages (highest-accuracy multilingual ModernBERT/mmBERT guardrail in the family)
- Labels (8 independent sigmoids):
toxicity,severe_toxicity,obscene,threat,insult,identity_attack,sexual_explicit(exact 7 labels used byprotectai/llm-guard'sToxicityscanner) +unsafe_ai_content(modern LLM/agent safety hazards). - Drop-in
llm-guardcompatibility: Verified live againstllm-guard[onnxruntime]==0.3.16(PyTorch:PASS,ONNX CPU:PASS) — see exact scope and caveats below. - Model Family (
Tamarillo/toxicity-safety-guard):Tamarillo/toxicity-safety-guard-tiny-en— 32.0M, English-only, ultra-fast CPU edge guardrailTamarillo/toxicity-safety-guard-small— 140.6M, 17+ languages, balanced accuracy & speedTamarillo/toxicity-safety-guard-base— 307.5M, 17+ languages, highest accuracy
Quickstart
Requires transformers>=4.48.0 (native ModernBERT support, zero trust_remote_code).
pip install "transformers>=4.48.0" torch
1. Transformers Pipeline (Zero trust_remote_code, All 8 Heads)
from transformers import pipeline
clf = pipeline(
"text-classification",
model="Tamarillo/toxicity-safety-guard-base",
top_k=None,
function_to_apply="sigmoid",
truncation=True,
max_length=2048,
)
scores = {d["label"]: round(d["score"], 4) for d in clf("You are a disgusting idiot, shut up and get lost.")[0]}
print(scores)
# Example output: {"unsafe_ai_content": 0.9914, "insult": 0.9404, "toxicity": 0.9319, "obscene": 0.2093, "severe_toxicity": 0.0689, "identity_attack": 0.0139, "threat": 0.0083, "sexual_explicit": 0.0032}
2. Drop-In Replacement for protectai/llm-guard (Toxicity Scanner)
Works with zero scanner code changes on llm-guard==0.3.16 (both PyTorch and CPU ONNX via pip install "llm-guard[onnxruntime]==0.3.16"):
from llm_guard.input_scanners import Toxicity
from llm_guard.model import Model
tamarillo_model = Model(
path="Tamarillo/toxicity-safety-guard-base",
onnx_path="Tamarillo/toxicity-safety-guard-base",
onnx_subfolder="onnx",
onnx_filename="model.onnx",
pipeline_kwargs={
"top_k": None,
"function_to_apply": "sigmoid",
"return_token_type_ids": False,
"max_length": 2048, # overrides llm-guard's default 512-token cap
"truncation": True,
},
)
scanner = Toxicity(model=tamarillo_model, threshold=0.5, use_onnx=True)
sanitized_prompt, is_valid, risk_score = scanner.scan("You are a disgusting idiot and everyone hates you.")
print(is_valid, risk_score) # False 0.9
Important
llm-guardcaveat:llm-guard'sToxicity.scan()filters strictly on its 7_toxic_labels(toxicity,severe_toxicity,obscene,threat,insult,identity_attack,sexual_explicit) and ignores the 8thunsafe_ai_contenthead. To score both toxicity and modern LLM/agent safety hazards (unsafe_ai_content), call the model directly viatransformers.pipelineor ONNX Runtime.Non-drop-in peers: This model is not a zero-code drop-in for
unitary/toxic-bert(different label names:toxic/identity_hate) orgarak'ss-nlp/roberta_toxicity_classifier(2-class softmaxneutral/toxic); migrating from those requires a 3-linetransformers/ONNX adapter.
3. Direct ONNX Runtime (CPU Sidecar)
pip install onnxruntime huggingface_hub "transformers>=4.48.0" numpy
import numpy as np
import onnxruntime as ort
from huggingface_hub import hf_hub_download
from transformers import AutoConfig, AutoTokenizer
repo = "Tamarillo/toxicity-safety-guard-base"
cfg = AutoConfig.from_pretrained(repo)
tok = AutoTokenizer.from_pretrained(repo)
onnx_path = hf_hub_download(repo, "onnx/model.onnx") # or "onnx/model_fp16.onnx"
sess = ort.InferenceSession(onnx_path, providers=["CPUExecutionProvider"])
enc = tok(["How do I write a Suricata rule to detect SQLi?"], padding=True, truncation=True, max_length=2048, return_tensors="np")
logits = sess.run(["logits"], {"input_ids": enc["input_ids"].astype(np.int64), "attention_mask": enc["attention_mask"].astype(np.int64)})[0]
logits_f32 = logits.astype(np.float32) # cast to float32 before exp() for safe FP16 ONNX usage
probs = (1.0 / (1.0 + np.exp(-np.clip(logits_f32, -30.0, 30.0))))[0]
scores = {cfg.id2label[i]: round(float(probs[i]), 4) for i in range(len(probs))}
print(scores)
Benchmarks (Unified Evaluation)
All metrics below are proportions in [0.000, 1.000] evaluated on shared held-out test splits (subsampled for generative Qwen3Guard-Gen-0.6B, marked with *; reproducible script: scripts/eval_suite.py; raw JSON: eval_results.json) using each model's native activation (sigmoid for multi-label encoders, softmax for s-nlp/KoalaAI, official chat-template decoding for Qwen3Guard-Gen-0.6B).
- In-Distribution (ID) held-out suites (
Civil Commentsis also ID forunitary/*):Civil Comments(google/civil_commentstest split,n=3,000: 1,500 pos / 1,500 neg;*n=600forQwen3Guard)Aegis-v2(nvidia/Aegis-AI-Content-Safety-Dataset-2.0official test split,n=2,500;*n=600forQwen3Guard)Forensic Benign(n=400, deterministic split-disjoint defensive cybersecurity, SIEM/YARA/Suricata, clinical pharmacology, and historical education prompts generated byscripts/data_builder.py— lower FPR is better)
- Strictly Zero-Shot Out-of-Distribution (OOD) suites (NEVER seen in Tamarillo train/val; whitespace-normalized MD5 deduplicated):
OOD JBB(JailbreakBench/JBB-Behaviors, MIT,n=200: 100 harmful + 100 matched benign behaviors)OOD OR-Bench-Hard(bench-llm/or-benchor-bench-hard-1k, CC-BY-4.0,n=1,000;*n=400forQwen3Guard— adversarial over-refusal benign prompts; lower FPR is better)OOD TextDetox(textdetox/multilingual_toxicity_dataset, 14 non-English languages, OpenRAIL++,n=2,250[150/lang];*n=600[40/lang] forQwen3Guard— eval-only, never trained on)
| Model | Params | License | Civil Tox AUC (ID) | Civil 7-Head AUC (ID) | Aegis-v2 F1 (ID) | OOD JBB F1 / AUC | OOD OR-Bench FPR (Tox / Safe ↓) | OOD TextDetox Non-EN AUC | Forensic Benign FPR ↓ | L4 GPU p50 (64 / 2048 tok) |
|---|---|---|---|---|---|---|---|---|---|---|
| Tamarillo/toxicity-safety-guard-tiny-en | 32.0M | Apache-2.0 | 0.956 | 0.977 | 0.828 | 0.754 / 0.887 | 0.382 / 0.836 | 0.604 | 0.000 | 11.4 ms / 27.5 ms |
| Tamarillo/toxicity-safety-guard-small | 140.6M | Apache-2.0 | 0.957 | 0.979 | 0.830 | 0.782 / 0.885 | 0.560 / 0.883 | 0.735 | 0.000 | 24.3 ms / 34.8 ms |
| Tamarillo/toxicity-safety-guard-base | 307.5M | Apache-2.0 | 0.959 | 0.979 | 0.852 | 0.797 / 0.927 | 0.589 / 0.837 | 0.760 | 0.000 | 24.1 ms / 35.0 ms |
unitary/unbiased-toxic-roberta (llm-guard default) |
124.7M | Apache-2.0 | 0.964 | 0.976 | 0.280 | 0.075 / 0.612 | 0.000 / 0.000 | 0.554 | 0.000 | 9.6 ms / 9.1 ms |
unitary/toxic-bert |
109.5M | Apache-2.0 | 0.912 | 0.890 | 0.249 | 0.093 / 0.679 | 0.000 / 0.000 | 0.589 | 0.000 | 9.3 ms / 8.9 ms |
unitary/multilingual-toxic-xlm-roberta |
278.0M | Apache-2.0 | 0.956 | 0.956 | 0.264 | 0.020 / 0.640 | 0.000 / 0.000 | 0.669 | 0.000 | 9.5 ms / 9.1 ms |
s-nlp/roberta_toxicity_classifier (garak default) |
124.7M | OpenRAIL++ | 0.974 | 0.974 | 0.290 | 0.094 / 0.687 | 0.000 / 0.000 | 0.631 | 0.000 | 9.5 ms / 9.2 ms |
KoalaAI/Text-Moderation |
139.2M | OpenRAIL | 0.781 | 0.781 | 0.277 | 0.191 / 0.618 | 0.000 / 0.000 | 0.596 | 0.000 | 23.6 ms / 29.2 ms |
Qwen/Qwen3Guard-Gen-0.6B* (0.6B generative) |
596.0M | Apache-2.0 | 0.503 | 0.503 | 0.739 | 0.861 / 0.845 | 0.537 / 0.537 | 0.576 | 0.147 | 1013.3 ms / 1056.3 ms |
Evaluation transparency notes:
- Threshold & head aggregation: All binary F1 and FPR metrics use fixed threshold
0.50. For Tamarillo models,Aegis-v2 F1andOOD JBB F1 / AUCscore head #7 (unsafe_ai_content),OOD TextDetoxscores head #0 (toxicity),OOD OR-Bench FPRreports bothtoxicity(head #0) andunsafe_ai_content(head #7) separately, andForensic Benign FPRscoresmax(toxicity, unsafe_ai_content). For legacy multi-head toxicity baselines (unitary/*),Aegis-v2,OOD JBB, andForensic Benignusemax(toxicity heads).- Legacy encoders on
OR-Bench-Hard-1k(0.000FPR): Legacy web-toxicity classifiers (unitary/*,s-nlp,KoalaAI) achieve0.000FPR onOR-Bench-Hard-1kbecause they do not detect non-profane AI safety hazards at all (scoring only0.020–0.191F1 onOOD JBB-Behaviorsand0.115–0.138recall onSalad-Data).Qwen/Qwen3Guard-Gen-0.6B(subsampled & discrete outputs):* Evaluated on smaller subsets (n=600Civil/Aegis/TextDetox,n=400OR-Bench,n=80needle) due to generative decoding cost, and reports official strictSafety: Unsafeclassification (countingControversialas unsafe raisesAegis-v2F1 to0.850, lowersOOD JBBF1 to0.765, and raisesOR-Bench-HardFPR to0.753). BecauseQwen3Guard-Genoutputs discrete0/1text decisions rather than continuous probabilities, its0.503Civil Comments ROC-AUC reflects near-zero recall on mild web profanity rather than an apples-to-apples continuous-score comparison.- GPU latency methodology: All GPU latencies are
batch_size=1p50 overn=30timed runs (n=20/15forQwen3Guard) after8warmup passes on the same NVIDIA L4 (bf16; FP32 forKoalaAI/Text-Moderationto avoid DeBERTabf16attention overflow; 512-token baselines run at their native 512-token cap on the 2,048-token probe).small(24.3 ms) andbase(24.1 ms) share nearly identical 64-token L4 latency because both have 22 layers and short-sequence GPU inference is kernel-launch bound.
Long-Context Late-Harm Needle Recall (In-Distribution Format, Held-Out Test Needles, Single-Pass Truncation)
Held-out test needles (40 Aegis-v2 unsafe + 40 Civil Comments toxic) embedded after ~250, ~800, ~1,600, and ~3,200 tokens of benign prose (n=320, 80 per depth bucket; *n=80 for Qwen3Guard; proportion recalled via max(toxicity, unsafe_ai_content) >= 0.5).
| Model | Eval Max Tokens | Recall @ ~250 tok | Recall @ ~800 tok | Recall @ ~1,600 tok | Recall @ ~3,200 tok |
|---|---|---|---|---|---|
| Tamarillo/toxicity-safety-guard-tiny-en | 4096 | 0.725 | 0.863 | 0.575 | 0.875 |
| Tamarillo/toxicity-safety-guard-small | 4096 | 0.688 | 0.850 | 0.487 | 0.762 |
| Tamarillo/toxicity-safety-guard-base | 4096 | 0.750 | 0.887 | 0.662 | 0.887 |
unitary/unbiased-toxic-roberta (llm-guard default) |
512 | 0.138 | 0.000 | 0.000 | 0.000 |
unitary/toxic-bert |
512 | 0.000 | 0.000 | 0.000 | 0.000 |
unitary/multilingual-toxic-xlm-roberta |
512 | 0.013 | 0.000 | 0.000 | 0.000 |
s-nlp/roberta_toxicity_classifier (garak default) |
512 | 0.037 | 0.000 | 0.000 | 0.000 |
KoalaAI/Text-Moderation |
512 | 0.225 | 0.075 | 0.087 | 0.037 |
Qwen/Qwen3Guard-Gen-0.6B* (0.6B generative) |
4096 | 0.150 | 0.050 | 0.000 | 0.000 |
Needle evaluation note: Haystack construction matches our in-distribution long-context training format using strictly held-out test needles. Legacy web-toxicity baselines score
0.000–0.225even at ~250 tokens (within their 512-token cap) because half of the needles are non-profaneAegis-v2AI-safety prompts and benign prefix dilution reduces web-toxicity scores. Inscripts/data_builder.py, each depth bucket evaluates 80 samples drawn from a distinct 20-needle modulo slice (i % 4, each embedded in 4 distinct benign haystacks), so bucket-to-bucket variance (including the lower recall at ~1,600 tokens across all three Tamarillo variants) reflects needle-slice difficulty rather than a positional dead zone. Legacy 512-token models truncate past token 512 in single-pass inference (sliding-window chunking is an alternative with orchestration overhead).
ONNX Exports, Parity & Latency (n=30 runs)
All ONNX exports are verified against PyTorch FP32 reference probabilities on both short (~64 tok) and long (2,048 tok) inputs with a hard >=0.995 prediction agreement release gate. CPU latency measured at batch_size=1 (n=30 timed runs after 5 warmups) on 4 vCPU threads (Intel Xeon, GCP a2-ultragpu-1g, onnxruntime, CPUExecutionProvider). Tip: Use onnx/model.onnx (FP32) for lowest x86 CPU latency, and onnx/model_fp16.onnx (FP16) for a 50% smaller download/memory footprint or GPU/browser inference.
| Artifact | File Size | Parity (Short) | Parity (2,048 tok) | CPU p50 / p95 (64 tok) | CPU p50 / p95 (2,048 tok) |
|---|---|---|---|---|---|
FP32 (onnx/model.onnx) |
1173.7 MB | 1.0000 (max Δ 0.0000) |
1.0000 (max Δ 0.0000) |
53.7 ms / 54.1 ms | 3334.1 ms / 3340.2 ms |
FP16 (onnx/model_fp16.onnx) |
587.0 MB | 1.0000 (max Δ 0.0019) |
1.0000 (max Δ 0.0007) |
60.8 ms / 61.3 ms | 4353.7 ms / 4373.5 ms |
Note on INT8 ONNX: Per-channel dynamic INT8 quantization was evaluated and intentionally excluded by our hard release gate (
>=0.995agreement, max prob Δ<=0.05; measured short agreement0.9141). Useonnx/model.onnx(FP32) oronnx/model_fp16.onnx(FP16, 50% smaller,1.0000parity).
- PyTorch GPU (NVIDIA L4,
bf16,batch_size=1):24.1 msp50 at 64 tokens;35.0 msp50 at 2,048 tokens.
Training Data, Hygiene & Reproducibility
Trained exclusively on commercially clean (CC0-1.0, CC-BY-4.0, MIT, Apache-2.0) datasets with masked continuous soft-label BCEWithLogitsLoss (zero CC-BY-NC, zero OpenRAIL/OpenRAIL++, zero gated datasets in training):
google/civil_comments(CC0-1.0): Continuous soft-label annotator probabilities across all 7 toxicity heads (prioritizing all rare-head positives) plus calibratedunsafe_ai_contenttargets on unambiguous benign/severe comments.ToxicityPrompts/PolyGuardMix(CC-BY-4.0): Balanced prompt/response safety and adversarial-benign corpus (17 languages) with MLCommons S1–S14 category-aware sub-head mapping.nvidia/Aegis-AI-Content-Safety-Dataset-2.0(CC-BY-4.0, official train/validation splits).OpenSafetyLab/Salad-Data(Apache-2.0, capped unsafe + jailbreak-enhanced prompts, hash-split 80/10/10).argilla/ultrafeedback-binarized-preferences-cleaned(MIT) andCohereForAI/aya_dataset(Apache-2.0): Benign user instructions to reduce "question = unsafe" over-refusal bias.- Split-disjoint benign developer/cybersecurity/forensic hard negatives and balanced log-spaced long-context haystacks (up to
3,584tokens). - Training stats:
425,296deduplicated training examples,2.5epochs,lr=2.5e-05,max_length=3584, checkpoint selected strictly by validationselection_score(0.95125). - Reproducible training, ONNX export, evaluation, and integration test scripts are bundled directly under
scripts/.
Known Limitations & Where Baselines Beat Us
- Single-head English web toxicity (
Civil Commentshead #0): WhileTamarillo/toxicity-safety-guard-baseachieves0.9797-head macro ROC-AUC (beatingunitary/unbiased-toxic-robertaat0.976andunitary/toxic-bertat0.890), single-task English web-comment classifierss-nlp/roberta_toxicity_classifier(0.974,OpenRAIL++) andunitary/unbiased-toxic-roberta(0.964, trained on all 1.8M Civil Comments rows) edge out this model (0.959) on the standalone Englishtoxicityhead and run faster on short 512-token GPU inputs (~9.5 msvs.24.1 ms). - Generative LLM reasoning & over-refusal (
Qwen3Guard-Gen-0.6B):Qwen/Qwen3Guard-Gen-0.6B(596M autoregressive decoder) beatsTamarillo/toxicity-safety-guard-baseon strict zero-shotOOD JBBF1 (0.861vs.0.797, thoughTamarillo/toxicity-safety-guard-baseachieves0.927threshold-free ROC-AUC) and achieves lowerOOD OR-Bench-Hard-1kFPR (0.537strict vs.0.837onunsafe_ai_contentat threshold0.50). However,Qwen3Guard-Gen-0.6Bis42xslower at 64 tokens (1,013.3 msvs.24.1 ms) and30xslower at 2,048 tokens on L4 GPU, incurs0.147FPR onForensic Benign(vs.0.000), fails on long-context needles (0.000–0.050at 800–3,200 tokens), and cannot run as a lightweight CPU ONNX sidecar. - CPU latency at 2,048 tokens: On 4 vCPU threads (
onnxruntime), FP32 latency forTamarillo/toxicity-safety-guard-baseis53.7 msat 64 tokens but grows to3334.1 msat 2,048 tokens due to self-attention scaling. For high-throughput long-context workloads, deploy on GPU (35.0 msp50 on NVIDIA L4 at 2,048 tokens) or pair with a fast pre-filter. - Language scope: Trained across 17 languages from
PolyGuardMixplusCohereForAI/aya_dataset(0.760zero-shot non-EN macro ROC-AUC onOOD TextDetox, beatingunitary/multilingual-toxic-xlm-robertaat0.669), but performance on low-resource languages outside those corpora is unverified. - Context window extrapolation: The backbone supports up to
8,192tokens, while fine-tuning and needle evaluation covered up to3,584tokens (~3,200-token needle depth). Performance beyond3,584tokens relies on backbone RoPE extrapolation and is not directly benchmarked here. - Over-refusal on
OR-Bench-Hard-1k: Adversarial-benign prompts deliberately crafted to mimic harmful requests trigger elevatedunsafe_ai_contentscores (0.837FPR at default0.50threshold;0.589on thetoxicityhead). Production users should tune the threshold per head (0.50–0.85) and monitortoxicityvs.unsafe_ai_contentindependently.
Gather-INT8 Quantized ONNX (onnx/model_quantized.onnx — 611.38 MB, 1.92x smaller)
- Verified Parity (
onnx/quantization_check.json):100.0%prediction agreement vs. FP32 ONNX (mean abs probability diff0.00105, max0.01774;166.2 ms4-thread CPU p50 @ 256 tokens). - Browser WASM / Node.js (
@huggingface/transformersv3): pass{ dtype: "q8" }to loadonnx/model_quantized.onnxautomatically.
- Downloads last month
- 21
Model tree for Tamarillo/toxicity-safety-guard-base
Base model
jhu-clsp/mmBERT-base