Datasets:
Download run_benchmark.py from henny52/chatmod-bench: direct link, hf CLI and curl.
- Browser
- Download file 7.88 kB
-
https://huggingface.co/datasets/henny52/chatmod-bench/resolve/main/run_benchmark.py
- Command line
-
hf download hf://datasets/henny52/chatmod-bench/run_benchmark.py
-
curl -L -o run_benchmark.py https://huggingface.co/datasets/henny52/chatmod-bench/resolve/main/run_benchmark.py
7.88 kB
| """Run ChatMod Bench against a moderation model and print the scores. | |
| Examples: | |
| python run_benchmark.py --model axo-native-small-preview | |
| python run_benchmark.py --model omni # needs OPENAI_API_KEY | |
| python run_benchmark.py --model qwen3guard-0.6b # also 4b / 8b | |
| python run_benchmark.py --predictions my_model.jsonl # bring your own predictions | |
| A predictions file has one line per case: | |
| {"id": "cmb-chat-de-...", "flagged": true, "score": 0.93} | |
| `score` is optional and only used for ROC-AUC. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| import time | |
| import urllib.error | |
| import urllib.request | |
| from collections import defaultdict | |
| from pathlib import Path | |
| HERE = Path(__file__).resolve().parent | |
| QWEN3GUARD = { | |
| "qwen3guard-0.6b": "Qwen/Qwen3Guard-Gen-0.6B", | |
| "qwen3guard-4b": "Qwen/Qwen3Guard-Gen-4B", | |
| "qwen3guard-8b": "Qwen/Qwen3Guard-Gen-8B", | |
| } | |
| def load_cases() -> list[dict]: | |
| with (HERE / "test.jsonl").open(encoding="utf-8") as fh: | |
| return [json.loads(line) for line in fh if line.strip()] | |
| def run_axo_native(cases: list[dict]) -> list[dict]: | |
| from huggingface_hub import snapshot_download | |
| path = snapshot_download("henny52/axo-native-small-preview") | |
| sys.path.insert(0, path) | |
| from axo_native import AxoNativeSmall, AxoNativeTokenizer | |
| model = AxoNativeSmall.from_pretrained(path) | |
| tokenizer = AxoNativeTokenizer.from_pretrained(path) | |
| out = [] | |
| for start in range(0, len(cases), 64): | |
| batch = [c["text"] for c in cases[start : start + 64]] | |
| for r in model.predict_json(batch, tokenizer, level="medium", explain=False): | |
| out.append({"flagged": r.action != "allow", "score": r.score}) | |
| return out | |
| def run_omni(cases: list[dict]) -> list[dict]: | |
| key = os.environ.get("OPENAI_API_KEY") | |
| if not key: | |
| raise SystemExit("Set OPENAI_API_KEY to run omni-moderation.") | |
| out = [] | |
| for start in range(0, len(cases), 16): | |
| body = json.dumps( | |
| { | |
| "model": "omni-moderation-latest", | |
| "input": [c["text"] for c in cases[start : start + 16]], | |
| } | |
| ).encode("utf-8") | |
| for attempt in range(6): | |
| req = urllib.request.Request( | |
| "https://api.openai.com/v1/moderations", | |
| data=body, | |
| method="POST", | |
| headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"}, | |
| ) | |
| try: | |
| with urllib.request.urlopen(req, timeout=90) as resp: | |
| results = json.loads(resp.read().decode("utf-8"))["results"] | |
| break | |
| except urllib.error.HTTPError as err: | |
| if err.code not in {429, 500, 502, 503, 504} or attempt == 5: | |
| raise | |
| time.sleep(2**attempt) | |
| for item in results: | |
| out.append( | |
| {"flagged": bool(item["flagged"]), "score": max(item["category_scores"].values())} | |
| ) | |
| return out | |
| def run_qwen3guard(name: str, cases: list[dict]) -> list[dict]: | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| repo = QWEN3GUARD[name] | |
| tokenizer = AutoTokenizer.from_pretrained(repo) | |
| model = AutoModelForCausalLM.from_pretrained(repo, dtype="auto", device_map="auto") | |
| labels = {"Unsafe": 1.0, "Controversial": 0.5, "Safe": 0.0} | |
| out = [] | |
| for i, case in enumerate(cases, 1): | |
| prompt = tokenizer.apply_chat_template( | |
| [{"role": "user", "content": case["text"]}], | |
| tokenize=False, | |
| add_generation_prompt=True, | |
| ) | |
| inputs = tokenizer([prompt], return_tensors="pt").to(model.device) | |
| with torch.no_grad(): | |
| generated = model.generate(**inputs, max_new_tokens=32, do_sample=False) | |
| answer = tokenizer.decode( | |
| generated[0][inputs.input_ids.shape[1] :], skip_special_tokens=True | |
| ) | |
| verdict = next((label for label in labels if f"Safety: {label}" in answer), "Safe") | |
| out.append({"flagged": verdict != "Safe", "score": labels[verdict]}) | |
| if i % 50 == 0: | |
| print(f"{i}/{len(cases)}", file=sys.stderr) | |
| return out | |
| def load_predictions(path: Path, cases: list[dict]) -> list[dict]: | |
| preds = {} | |
| with path.open(encoding="utf-8") as fh: | |
| for line in fh: | |
| if line.strip(): | |
| row = json.loads(line) | |
| preds[row["id"]] = row | |
| missing = [c["id"] for c in cases if c["id"] not in preds] | |
| if missing: | |
| raise SystemExit(f"{len(missing)} cases have no prediction, e.g. {missing[0]}") | |
| return [ | |
| { | |
| "flagged": bool(preds[c["id"]]["flagged"]), | |
| "score": float(preds[c["id"]].get("score", preds[c["id"]]["flagged"])), | |
| } | |
| for c in cases | |
| ] | |
| def roc_auc(labels: list[int], scores: list[float]) -> float | None: | |
| pos = [s for s, y in zip(scores, labels, strict=True) if y == 1] | |
| neg = [s for s, y in zip(scores, labels, strict=True) if y == 0] | |
| if not pos or not neg: | |
| return None | |
| wins = sum((p > n) + 0.5 * (p == n) for p in pos for n in neg) | |
| return wins / (len(pos) * len(neg)) | |
| def metrics(rows: list[tuple[dict, dict]]) -> dict: | |
| tp = sum(1 for c, p in rows if p["flagged"] and c["label"] == 1) | |
| tn = sum(1 for c, p in rows if not p["flagged"] and c["label"] == 0) | |
| fp = sum(1 for c, p in rows if p["flagged"] and c["label"] == 0) | |
| fn = sum(1 for c, p in rows if not p["flagged"] and c["label"] == 1) | |
| def f1(tp_: int, fp_: int, fn_: int) -> float: | |
| return 2 * tp_ / max(1, 2 * tp_ + fp_ + fn_) | |
| return { | |
| "n": len(rows), | |
| "accuracy": (tp + tn) / max(1, len(rows)), | |
| "macro_f1": (f1(tp, fp, fn) + f1(tn, fn, fp)) / 2, | |
| "false_positive_rate": fp / max(1, fp + tn), | |
| "false_negative_rate": fn / max(1, fn + tp), | |
| "roc_auc": roc_auc([c["label"] for c, _ in rows], [p["score"] for _, p in rows]), | |
| } | |
| def main() -> int: | |
| parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | |
| source = parser.add_mutually_exclusive_group(required=True) | |
| source.add_argument("--model", choices=["axo-native-small-preview", "omni", *QWEN3GUARD]) | |
| source.add_argument("--predictions", type=Path) | |
| parser.add_argument("--out", type=Path, help="write per-case predictions as JSONL") | |
| parser.add_argument("--limit", type=int, help="only the first N cases (quick check)") | |
| args = parser.parse_args() | |
| cases = load_cases() | |
| if args.limit: | |
| cases = cases[: args.limit] | |
| if args.predictions: | |
| preds = load_predictions(args.predictions, cases) | |
| elif args.model == "axo-native-small-preview": | |
| preds = run_axo_native(cases) | |
| elif args.model == "omni": | |
| preds = run_omni(cases) | |
| else: | |
| preds = run_qwen3guard(args.model, cases) | |
| if args.out: | |
| with args.out.open("w", encoding="utf-8") as fh: | |
| for c, p in zip(cases, preds, strict=True): | |
| fh.write(json.dumps({"id": c["id"], **p}) + "\n") | |
| rows = list(zip(cases, preds, strict=True)) | |
| groups: dict[str, list] = defaultdict(list) | |
| for c, p in rows: | |
| groups[f"{c['source']} {c['lang']}"].append((c, p)) | |
| print( | |
| f"{'subset':16s} {'n':>4s} {'acc':>7s} {'macroF1':>8s} {'FPR':>7s} {'FNR':>7s} {'AUC':>6s}" | |
| ) | |
| for name, items in [("all", rows), *sorted(groups.items())]: | |
| m = metrics(items) | |
| auc = f"{m['roc_auc']:.3f}" if m["roc_auc"] is not None else " - " | |
| print( | |
| f"{name:16s} {m['n']:4d} {m['accuracy']:7.1%} {m['macro_f1']:8.3f} " | |
| f"{m['false_positive_rate']:7.1%} {m['false_negative_rate']:7.1%} {auc:>6s}" | |
| ) | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |