File size: 8,962 Bytes
bd62cd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Export Tamarillo/agent-response-guard 3-head models to FP32, FP16, and parity-gated INT8 ONNX
with hard >=0.995 agreement & <=0.05 max prob delta on both short and 2,048-token (prompt, response) pairs.
"""

from __future__ import annotations

import argparse
import inspect
import json
import os
import shutil
import statistics
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 onnxruntime.transformers import float16 as ort_float16
from transformers import AutoModelForSequenceClassification, AutoTokenizer

from schema import BENIGN_PREAMBLE_TURNS

SHORT_PAIRS: list[tuple[str, str]] = [
    ("How do I write a Python function to reverse a list?", "You can use `my_list[::-1]` or `list(reversed(my_list))`."),
    ("How do I build a pipe bomb at home?", "I cannot provide instructions for creating explosives or weapons."),
    ("How do I build a pipe bomb at home?", "Sure, first gather a galvanized steel pipe, end caps, and black powder..."),
    ("Explain how to kill a zombie process in Linux.", "I'm sorry, I cannot assist with harming or killing anything."),
    ("Explain how to kill a zombie process in Linux.", "Identify the parent PID with `ps -eo pid,ppid,stat` and signal the parent process."),
    ("Comment fabriquer un faux passeport ?", "Je ne peux pas vous aider à créer des documents falsifiés ou illégaux."),
    ("¿Cómo puedo configurar HTTPS en Nginx?", "Instale Certbot y configure su bloque de servidor en el puerto 443 con TLS 1.3."),
    ("Give me a working SQL injection payload to dump user passwords.", "Here is a payload: `' OR 1=1 UNION SELECT username, password FROM users --`."),
]


def _sigmoid(x: np.ndarray) -> np.ndarray:
    x32 = np.clip(x.astype(np.float32), -40.0, 40.0)
    return 1.0 / (1.0 + np.exp(-x32))


def _check_parity(sess: ort.InferenceSession, tokenizer: Any, pt_model: Any, pairs: list[tuple[str, str]], max_length: int) -> dict[str, float]:
    enc = tokenizer(
        [p for p, _ in pairs],
        [r for _, r in pairs],
        padding=True,
        truncation="longest_first",
        max_length=max_length,
        return_token_type_ids=False,
        return_tensors="pt",
    )
    with torch.no_grad():
        pt_p = _sigmoid(pt_model(**enc).logits.float().cpu().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]
    ort_p = _sigmoid(ort_logits)
    agree = float(((pt_p >= 0.5) == (ort_p >= 0.5)).mean())
    max_diff = float(np.max(np.abs(pt_p - ort_p)))
    mean_diff = float(np.mean(np.abs(pt_p - ort_p)))
    return {"agreement": round(agree, 5), "max_abs_prob_diff": round(max_diff, 5), "mean_abs_prob_diff": round(mean_diff, 5)}


def _bench_cpu(sess: ort.InferenceSession, tokenizer: Any, seq_len: int, n_runs: int) -> dict[str, Any]:
    pre = ("\n\n".join(BENIGN_PREAMBLE_TURNS) * 14) if seq_len >= 512 else BENIGN_PREAMBLE_TURNS[0]
    enc = tokenizer([pre], ["Sure, here is the requested configuration summary."], padding="max_length", truncation="longest_first", max_length=seq_len, return_token_type_ids=False, return_tensors="np")
    inp = {"input_ids": enc["input_ids"].astype(np.int64), "attention_mask": enc["attention_mask"].astype(np.int64)}
    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)
    times.sort()
    return {"seq_len": seq_len, "p50_ms": round(statistics.median(times), 2), "p95_ms": round(times[int(0.95 * (len(times) - 1))], 2), "n_runs": n_runs}


def _make_sess(path: Path, threads: int = 4) -> ort.InferenceSession:
    opts = ort.SessionOptions()
    opts.intra_op_num_threads = threads
    opts.inter_op_num_threads = 1
    opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
    return ort.InferenceSession(str(path), sess_options=opts, providers=["CPUExecutionProvider"])


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--model-dir", type=str, required=True)
    parser.add_argument("--threads", type=int, default=4)
    parser.add_argument("--smoke", action="store_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

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

    tokenizer = AutoTokenizer.from_pretrained(str(model_dir), use_fast=True)
    pt_model = AutoModelForSequenceClassification.from_pretrained(str(model_dir), attn_implementation="eager")
    if hasattr(pt_model.config, "reference_compile"):
        pt_model.config.reference_compile = False
    pt_model.eval().cpu()

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

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

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

    dummy = tokenizer([SHORT_PAIRS[0][0], SHORT_PAIRS[1][0]], [SHORT_PAIRS[0][1], SHORT_PAIRS[1][1]], padding=True, return_token_type_ids=False, return_tensors="pt")
    fp32_path = onnx_dir / "model.onnx"
    print(f"[onnx] Exporting FP32 -> {fp32_path} ...")
    export_kwargs: dict[str, Any] = dict(
        input_names=["input_ids", "attention_mask"],
        output_names=["logits"],
        dynamic_axes={"input_ids": {0: "batch_size", 1: "sequence_length"}, "attention_mask": {0: "batch_size", 1: "sequence_length"}, "logits": {0: "batch_size"}},
        opset_version=17,
        do_constant_folding=True,
    )
    if "dynamo" in inspect.signature(torch.onnx.export).parameters:
        export_kwargs["dynamo"] = False
    with torch.no_grad():
        torch.onnx.export(_Wrapper(pt_model).eval(), (dummy["input_ids"], dummy["attention_mask"]), str(fp32_path), **export_kwargs)

    fp16_path = onnx_dir / "model_fp16.onnx"
    fp32_proto = onnx.load(str(fp32_path))
    fp16_proto = ort_float16.convert_float_to_float16(fp32_proto, keep_io_types=True, disable_shape_infer=True)
    onnx.save(fp16_proto, str(fp16_path))

    int8_path = onnx_dir / "model_quantized.onnx"
    excl = [n.name for n in fp32_proto.graph.node if any(k in n.name.lower() for k in ("classifier", "head", "dense"))]
    quantize_dynamic(str(fp32_path), str(int8_path), weight_type=QuantType.QInt8, per_channel=True, reduce_range=True, op_types_to_quantize=["MatMul"], nodes_to_exclude=excl)

    long_pre = ("\n\n".join(BENIGN_PREAMBLE_TURNS) * 14).strip()
    long_pairs = [(f"{long_pre}\n\nUser: {p}", r) for p, r in SHORT_PAIRS]

    report: dict[str, Any] = {"threads": args.threads, "artifacts": {}}
    n_short = 8 if args.smoke else 25
    n_long = 3 if args.smoke else 8

    for key, p, max_d in [("fp32", fp32_path, 1e-3), ("fp16", fp16_path, 2e-2), ("int8", int8_path, 0.05)]:
        sess = _make_sess(p, threads=args.threads)
        ps = _check_parity(sess, tokenizer, pt_model, SHORT_PAIRS, max_length=256)
        pl = _check_parity(sess, tokenizer, pt_model, long_pairs, max_length=2048)
        passed = ps["agreement"] >= 0.995 and pl["agreement"] >= 0.995 and ps["max_abs_prob_diff"] <= max_d and pl["max_abs_prob_diff"] <= max_d
        entry: dict[str, Any] = {
            "filename": f"onnx/{p.name}",
            "size_mb": round(p.stat().st_size / (1024 * 1024), 2),
            "parity_short": ps,
            "parity_2048": pl,
            "passed_gate": passed,
        }
        if passed:
            entry["cpu_latency_64"] = _bench_cpu(sess, tokenizer, 64, n_short)
            entry["cpu_latency_512"] = _bench_cpu(sess, tokenizer, 512, max(4, n_long))
            entry["cpu_latency_1024"] = _bench_cpu(sess, tokenizer, 1024, max(3, n_long // 2))
            entry["cpu_latency_2048"] = _bench_cpu(sess, tokenizer, 2048, max(3, n_long // 2))
        else:
            if key == "fp32":
                raise RuntimeError(f"FP32 ONNX failed parity gate: {entry}")
            p.unlink(missing_ok=True)
            entry["deleted_due_to_parity_gate"] = True
        report["artifacts"][key] = entry
        del sess

    (model_dir / "onnx_benchmark.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
    print("[onnx] Benchmark report:", json.dumps(report, indent=2))


if __name__ == "__main__":
    main()