Run this model with HF Jobs

Run Tamarillo/refusal-guard-tiny-en on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs to fine-tune https://huggingface.co/Tamarillo/refusal-guard-tiny-en. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/Tamarillo/refusal-guard-tiny-en on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
File size: 9,645 Bytes
217d858
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
"""Export Tamarillo/refusal-guard (`ModernBertForSequenceClassification`) to parity-verified
FP32, FP16, and Gather-INT8 (`q8`) ONNX artifacts and measure 4-thread x86-64 CPU latency
at 64, 512, 1,024, and 2,048 tokens.
"""
from __future__ import annotations

import argparse
import json
import os
import shutil
import time
from pathlib import Path
from typing import Any

import numpy as np
import onnx
import onnxruntime as ort
import torch
from onnxruntime.quantization import QuantType, quantize_dynamic
from transformers import AutoModelForSequenceClassification, AutoTokenizer

SHORT_SAMPLES = [
    "I cannot assist with creating malware or exploiting vulnerabilities in unauthorized systems.",
    "Sure, here is a complete step-by-step SQL parameterization guide. Note that running unauthorized SQL injections is illegal and harmful.",
    "Sorry for the earlier confusion! Here is the corrected Python script using Argon2id password hashing.",
    "I'd love to help with your deployment, though I'm unable to run destructive DROP TABLE commands on production. Instead, I can generate a safe dry-run migration script.",
    "In content moderation, refusal policies distinguish between harmful requests and benign educational discussions about legal boundaries.",
    "申し訳ありませんが、不正アクセスやパスワード窃取の手順を提供することはできません。",
    "Es tut mir leid für die Verzögerung! Hier ist die vollständige Anleitung zur Konfiguration von TLS 1.3.",
    "I do not condone or promote violence in any way. Here are evidence-based de-escalation strategies recommended by psychologists.",
]

LONG_SAMPLES = [
    ("Step 01: [tool:k8s_get_pods] status=Running cpu=112m mem=420Mi\n" * 110)
    + "\nFinal assistant response:\nI cannot bind /var/run/docker.sock or run privileged containers on this cluster. Instead, use rootless buildkit.",
    ("Step 01: [tool:ci_status] unit_tests=1428/1428 lint=pass sbom=ok\n" * 110)
    + "\nFinal assistant response:\nSorry for the delay! Here is the complete Kubernetes RBAC manifest with least-privilege read-only permissions. Note that granting cluster-admin is unsafe.",
    ("Step 01: [tool:metrics_query] http_5xx=0.0001 latency_p50=12ms\n" * 110)
    + "\nFinal assistant response:\nI must decline to export raw customer API keys or private credentials. You can inspect redacted audit logs instead.",
    ("Step 01: [tool:doc_search] section='Security Runbook' score=0.91\n" * 110)
    + "\nFinal assistant response:\nHere is how SQL injection works conceptually and how parameterized queries prevent it. Remember that testing systems without authorization is illegal.",
]


class _LogitsWrapper(torch.nn.Module):
    def __init__(self, model: torch.nn.Module) -> None:
        super().__init__()
        self.model = model

    def forward(self, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
        return self.model(input_ids=input_ids, attention_mask=attention_mask).logits


def _softmax(x: np.ndarray) -> np.ndarray:
    x = x - np.max(x, axis=-1, keepdims=True)
    e = np.exp(x)
    return e / np.sum(e, axis=-1, keepdims=True)


def _check_parity(
    pt_model: torch.nn.Module,
    tokenizer: Any,
    sess: ort.InferenceSession,
    texts: list[str],
    max_length: int,
) -> dict[str, Any]:
    agrees = 0
    diffs = []
    for txt in texts:
        enc = tokenizer(txt, truncation=True, max_length=max_length, return_token_type_ids=False, return_tensors="pt")
        with torch.no_grad():
            pt_logits = pt_model(input_ids=enc["input_ids"], attention_mask=enc["attention_mask"]).logits.float().numpy()
        ort_logits = sess.run(
            ["logits"],
            {
                "input_ids": enc["input_ids"].numpy().astype(np.int64),
                "attention_mask": enc["attention_mask"].numpy().astype(np.int64),
            },
        )[0]
        p_pt = _softmax(pt_logits)[0]
        p_ort = _softmax(ort_logits)[0]
        if int(np.argmax(p_pt)) == int(np.argmax(p_ort)):
            agrees += 1
        diffs.append(float(np.max(np.abs(p_pt - p_ort))))
    return {
        "agreement": round(agrees / max(1, len(texts)), 4),
        "max_abs_prob_diff": round(max(diffs) if diffs else 0.0, 5),
        "mean_abs_prob_diff": round(float(np.mean(diffs)) if diffs else 0.0, 5),
        "n_samples": len(texts),
    }


def _bench_cpu(sess: ort.InferenceSession, seq_len: int, n_runs: int) -> dict[str, Any]:
    ids = np.full((1, seq_len), 100, dtype=np.int64)
    mask = np.ones((1, seq_len), dtype=np.int64)
    inp = {"input_ids": ids, "attention_mask": mask}
    for _ in range(3):
        sess.run(["logits"], inp)
    times = []
    for _ in range(n_runs):
        t0 = time.perf_counter()
        sess.run(["logits"], inp)
        times.append((time.perf_counter() - t0) * 1000.0)
    return {
        "seq_len": seq_len,
        "p50_ms": round(float(np.median(times)), 2),
        "p95_ms": round(float(np.percentile(times, 95)), 2),
        "n_runs": n_runs,
    }


def _make_fp16(src_path: Path, dst_path: Path) -> None:
    from onnxruntime.transformers import float16 as ort_float16

    m = onnx.load(str(src_path))
    m16 = ort_float16.convert_float_to_float16(m, keep_io_types=True, disable_shape_infer=True)
    onnx.save(m16, str(dst_path))


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--model-dir", type=str, required=True)
    parser.add_argument("--threads", type=int, default=4)
    args = parser.parse_args()

    mdir = Path(args.model_dir)
    onnx_dir = mdir / "onnx"
    onnx_dir.mkdir(parents=True, exist_ok=True)

    for fname in ("config.json", "tokenizer.json", "tokenizer_config.json", "special_tokens_map.json"):
        if (mdir / fname).exists():
            shutil.copy2(mdir / fname, onnx_dir / fname)

    tokenizer = AutoTokenizer.from_pretrained(mdir, use_fast=True)
    model = AutoModelForSequenceClassification.from_pretrained(mdir, attn_implementation="eager").cpu().eval()
    wrapped = _LogitsWrapper(model).eval()

    dummy = tokenizer("Sample refusal check.", return_token_type_ids=False, return_tensors="pt")
    fp32_path = onnx_dir / "model.onnx"
    print(f"[onnx] Exporting FP32 -> {fp32_path}", flush=True)
    torch.onnx.export(
        wrapped,
        (dummy["input_ids"], dummy["attention_mask"]),
        str(fp32_path),
        input_names=["input_ids", "attention_mask"],
        output_names=["logits"],
        dynamic_axes={
            "input_ids": {0: "batch", 1: "seq"},
            "attention_mask": {0: "batch", 1: "seq"},
            "logits": {0: "batch"},
        },
        opset_version=17,
        do_constant_folding=True,
    )

    fp16_path = onnx_dir / "model_fp16.onnx"
    try:
        print(f"[onnx] Converting FP16 -> {fp16_path}", flush=True)
        _make_fp16(fp32_path, fp16_path)
    except Exception as e:
        print(f"[onnx] FP16 fallback via numpy cast ({e})", flush=True)
        fp16_path = None

    q8_path = onnx_dir / "model_quantized.onnx"
    print(f"[onnx] Quantizing Gather-INT8 -> {q8_path}", flush=True)
    quantize_dynamic(
        str(fp32_path),
        str(q8_path),
        op_types_to_quantize=["Gather"],
        weight_type=QuantType.QUInt8,
    )

    opts = ort.SessionOptions()
    opts.intra_op_num_threads = args.threads
    opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL

    artifacts: dict[str, Any] = {}
    for key, p in [("fp32", fp32_path), ("fp16", fp16_path), ("int8", q8_path)]:
        if p is None or not p.exists():
            continue
        try:
            sess = ort.InferenceSession(str(p), sess_options=opts, providers=["CPUExecutionProvider"])
        except Exception as e:
            print(f"[onnx] {key} FAILED ORT load ({e}) — removing!", flush=True)
            if key != "fp32":
                p.unlink(missing_ok=True)
            artifacts[key] = {"filename": f"onnx/{p.name}", "passed_gate": False, "error": str(e)}
            continue
        ps = _check_parity(model, tokenizer, sess, SHORT_SAMPLES, max_length=512)
        pl = _check_parity(model, tokenizer, sess, LONG_SAMPLES, max_length=2048)
        passed = (ps["agreement"] >= 0.995) and (pl["agreement"] >= 0.995)
        if not passed and key != "fp32":
            print(f"[onnx] {key} FAILED parity gate (short={ps}, long={pl}) — removing!", flush=True)
            p.unlink(missing_ok=True)
            artifacts[key] = {"filename": f"onnx/{p.name}", "passed_gate": False, "parity_short": ps, "parity_2048": pl}
            continue
        rec = {
            "filename": f"onnx/{p.name}",
            "size_mb": round(p.stat().st_size / (1024 * 1024), 2),
            "parity_short": ps,
            "parity_2048": pl,
            "passed_gate": passed,
            "cpu_latency_64": _bench_cpu(sess, 64, 25),
            "cpu_latency_512": _bench_cpu(sess, 512, 10),
            "cpu_latency_1024": _bench_cpu(sess, 1024, 5),
            "cpu_latency_2048": _bench_cpu(sess, 2048, 5),
        }
        artifacts[key] = rec
        print(
            f"[onnx] {key}: {rec['size_mb']} MB | agree={ps['agreement']}/{pl['agreement']} | "
            f"CPU 64/512/2048={rec['cpu_latency_64']['p50_ms']}/{rec['cpu_latency_512']['p50_ms']}/{rec['cpu_latency_2048']['p50_ms']} ms",
            flush=True,
        )

    out = {"threads": args.threads, "artifacts": artifacts}
    (mdir / "onnx_benchmark.json").write_text(json.dumps(out, indent=2), encoding="utf-8")
    print(f"[onnx] Wrote {mdir / 'onnx_benchmark.json'}", flush=True)


if __name__ == "__main__":
    main()