Image Classification
Transformers
ONNX
Safetensors
siglip
ai-image-detection
deepfake-detection
image-forensics
agent-forensics
siglip2
ai-image-detector
ai-detector
synthetic-image-detection
Instructions to use Tamarillo/ai-image-forensics-guard-base with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Tamarillo/ai-image-forensics-guard-base with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-classification", model="Tamarillo/ai-image-forensics-guard-base") pipe("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/hub/parrots.png")# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForImageClassification processor = AutoProcessor.from_pretrained("Tamarillo/ai-image-forensics-guard-base") model = AutoModelForImageClassification.from_pretrained("Tamarillo/ai-image-forensics-guard-base", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download scripts/export_image_onnx.py from Tamarillo/ai-image-forensics-guard-base: direct link, hf CLI and curl.
- Browser
- Download file 8.43 kB
-
https://huggingface.co/Tamarillo/ai-image-forensics-guard-base/resolve/main/scripts/export_image_onnx.py
- Command line
-
hf download hf://Tamarillo/ai-image-forensics-guard-base/scripts/export_image_onnx.py
-
curl -L -o export_image_onnx.py https://huggingface.co/Tamarillo/ai-image-forensics-guard-base/resolve/main/scripts/export_image_onnx.py
8.43 kB
| """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() | |