File size: 8,427 Bytes
1eecc00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Family #12 Step 1B-4: Export vision classifiers to FP32 & parity-gated dynamic INT8 ONNX,
verify parity across n=64 held-out real + fake validation images, and benchmark same-machine
4-thread x86 CPU ONNX latency (bs=1, p50 ms) for Tamarillo AND incumbents.
"""

from __future__ import annotations

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

import numpy as np
import onnxruntime as ort
import torch
from onnxruntime.quantization import QuantType, quantize_dynamic
from PIL import Image
from transformers import AutoImageProcessor, AutoModelForImageClassification

Image.MAX_IMAGE_PIXELS = None


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

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


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


def bench_cpu_onnx(onnx_path: Path, img_size: int, n_warmup: int = 5, n_runs: int = 25) -> dict[str, Any]:
    opts = ort.SessionOptions()
    opts.intra_op_num_threads = 4
    opts.inter_op_num_threads = 1
    sess = ort.InferenceSession(str(onnx_path), sess_options=opts, providers=["CPUExecutionProvider"])
    in_name = sess.get_inputs()[0].name
    x = np.random.randn(1, 3, img_size, img_size).astype(np.float32)
    for _ in range(n_warmup):
        sess.run(None, {in_name: x})
    times = []
    for _ in range(n_runs):
        t0 = time.perf_counter()
        sess.run(None, {in_name: x})
        times.append((time.perf_counter() - t0) * 1000.0)
    return {
        "p50_ms": round(float(np.median(times)), 2),
        "p90_ms": round(float(np.percentile(times, 90)), 2),
        "img_size": img_size,
    }


def verify_parity(pt_model: torch.nn.Module, onnx_path: Path, tensors: list[np.ndarray]) -> dict[str, Any]:
    opts = ort.SessionOptions()
    opts.intra_op_num_threads = 4
    sess = ort.InferenceSession(str(onnx_path), sess_options=opts, providers=["CPUExecutionProvider"])
    in_name = sess.get_inputs()[0].name

    pt_probs, ort_probs = [], []
    pt_model.eval()
    for arr in tensors:
        x_pt = torch.tensor(arr, dtype=torch.float32)
        with torch.no_grad():
            z_pt = pt_model(pixel_values=x_pt).logits.numpy()
        z_ort = sess.run(None, {in_name: arr.astype(np.float32)})[0].astype(np.float32)
        pt_probs.append(_softmax(z_pt)[0])
        ort_probs.append(_softmax(z_ort)[0])
    pa = np.stack(pt_probs)
    oa = np.stack(ort_probs)
    return {
        "n_samples": len(tensors),
        "max_abs_prob_diff": round(float(np.abs(pa - oa).max()), 5),
        "mean_abs_prob_diff": round(float(np.abs(pa - oa).mean()), 5),
        "argmax_agreement": round(float((pa.argmax(-1) == oa.argmax(-1)).mean()), 4),
    }


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--model-dir", type=str, required=True)
    ap.add_argument("--val-jsonl", type=str, required=True)
    ap.add_argument("--img-size", type=int, default=224)
    ap.add_argument("--baseline-repo", type=str, default="")
    ap.add_argument("--out-json", type=str, required=True)
    args = ap.parse_args()

    os.environ["HF_HOME"] = "/tmp/hf"
    target = args.baseline_repo or args.model_dir
    out_dir = Path("/tmp/baseline_onnx_img") if args.baseline_repo else Path(args.model_dir)
    onnx_dir = out_dir / "onnx"
    onnx_dir.mkdir(parents=True, exist_ok=True)

    proc = AutoImageProcessor.from_pretrained(target)
    model = AutoModelForImageClassification.from_pretrained(target).eval().cpu()
    wrapper = VisionOnnxWrapper(model).eval()

    # Load 64 balanced real/fake validation images for rigorous parity verification
    rows = [json.loads(l) for l in Path(args.val_jsonl).read_text(encoding="utf-8").splitlines() if l.strip()]
    reals = [r for r in rows if int(r["label"]) == 1][:32]
    fakes = [r for r in rows if int(r["label"]) == 0][:32]
    tensors = []
    for r in reals + fakes:
        try:
            im = Image.open(r["path"]).convert("RGB")
            arr = proc(images=im, return_tensors="np")["pixel_values"].astype(np.float32)
            tensors.append(arr)
        except Exception:
            pass

    fp32_path = onnx_dir / "model.onnx"
    dummy = torch.randn(1, 3, args.img_size, args.img_size, dtype=torch.float32)
    with torch.no_grad():
        torch.onnx.export(
            wrapper,
            (dummy,),
            str(fp32_path),
            input_names=["pixel_values"],
            output_names=["logits"],
            dynamic_axes={"pixel_values": {0: "batch_size"}, "logits": {0: "batch_size"}},
            opset_version=17,
            do_constant_folding=True,
        )

    p32 = verify_parity(model, fp32_path, tensors)
    b32 = bench_cpu_onnx(fp32_path, args.img_size)
    res: dict[str, Any] = {
        "model": target,
        "img_size": args.img_size,
        "artifacts": {
            "fp32": {
                "file": "onnx/model.onnx",
                "size_mb": round(fp32_path.stat().st_size / 1e6, 2),
                "parity": p32,
                "cpu_bench": b32,
            }
        },
    }
    print(f"[onnx] {target} FP32 ({res['artifacts']['fp32']['size_mb']} MB): parity={p32} bench={b32}", flush=True)

    if not args.baseline_repo:
        # 1. FP16 ONNX (half file size, near-zero diff — keep_io_types=True, parity-gated <= 0.015!)
        fp16_path = onnx_dir / "model_fp16.onnx"
        try:
            import onnx
            from onnxconverter_common import float16
            m_onnx = onnx.load(str(fp32_path))
            m_fp16 = float16.convert_float_to_float16(m_onnx, keep_io_types=True)
            onnx.save(m_fp16, str(fp16_path))
            p16 = verify_parity(model, fp16_path, tensors)
            if p16["max_abs_prob_diff"] <= 0.015 and p16["argmax_agreement"] >= 0.98:
                b16 = bench_cpu_onnx(fp16_path, args.img_size)
                res["artifacts"]["fp16"] = {
                    "file": "onnx/model_fp16.onnx",
                    "size_mb": round(fp16_path.stat().st_size / 1e6, 2),
                    "parity": p16,
                    "cpu_bench": b16,
                }
                print(f"[onnx] {target} FP16 KEPT ({res['artifacts']['fp16']['size_mb']} MB): parity={p16} bench={b16}", flush=True)
            else:
                fp16_path.unlink(missing_ok=True)
                res["fp16_rejected"] = p16
                print(f"[onnx] {target} FP16 REJECTED: {p16}", flush=True)
        except Exception as e:
            fp16_path.unlink(missing_ok=True)
            res["fp16_error"] = str(e)
            print(f"[onnx] {target} FP16 ERR: {e}", flush=True)

        # 2. Dynamic INT8 (gated on mean_abs_prob_diff <= 0.015 & argmax_agreement >= 0.98;
        # full-suite OOD AUC is also separately verified in eval_image_suite.py!)
        q8_path = onnx_dir / "model_quantized.onnx"
        try:
            quantize_dynamic(
                str(fp32_path),
                str(q8_path),
                weight_type=QuantType.QUInt8,
                op_types_to_quantize=["MatMul", "Gemm"],
            )
            p8 = verify_parity(model, q8_path, tensors)
            if p8["mean_abs_prob_diff"] <= 0.015 and p8["argmax_agreement"] >= 0.98:
                b8 = bench_cpu_onnx(q8_path, args.img_size)
                res["artifacts"]["int8"] = {
                    "file": "onnx/model_quantized.onnx",
                    "size_mb": round(q8_path.stat().st_size / 1e6, 2),
                    "parity": p8,
                    "cpu_bench": b8,
                }
                print(f"[onnx] {target} INT8 KEPT ({res['artifacts']['int8']['size_mb']} MB): parity={p8} bench={b8}", flush=True)
            else:
                q8_path.unlink(missing_ok=True)
                res["int8_rejected"] = p8
                print(f"[onnx] {target} INT8 REJECTED: {p8}", flush=True)
        except Exception as e:
            q8_path.unlink(missing_ok=True)
            res["int8_error"] = str(e)
            print(f"[onnx] {target} INT8 ERR: {e}", flush=True)
    else:
        fp32_path.unlink(missing_ok=True)

    Path(args.out_json).write_text(json.dumps(res, indent=2), encoding="utf-8")


if __name__ == "__main__":
    main()