mesmer-ai-image-detector / inference.py
mesmertech's picture
Model files for review (private; card to follow)
97a463b verified
Raw History Blame Contribute Delete
21.2 kB
#!/usr/bin/env python3
"""Mesmer AI Image Detector: standalone inference (CLI and Python).
pip install -r requirements.txt
python inference.py photo.jpg [more.png ...] # prints verdict, score and display p_ai per image
python inference.py --json photo.jpg # full result as JSON lines
python inference.py --heatmap photo.jpg # adds the experimental crop map (JSON)
from inference import Detector
det = Detector.from_pretrained() # this repo's files from the Hub, or a local folder path
r = det.predict("photo.jpg") # a path, bytes, a PIL image or an H x W x 3 uint8 RGB array
r["verdict"] # "likely_ai" | "uncertain" | "likely_real"
r["score"] # higher = more AI-like; compare with r["thresholds"]
r["p_ai"] # 0-1 display score (0.5 at the uncertain line, 0.9 at the likely-AI line), NOT a probability
On first use the two public backbones (timm/vit_pe_core_large_patch14_336.fb, 1.3 GB, and
timm/vit_pe_core_gigantic_patch14_448.fb, 7.5 GB) are downloaded from the Hub at pinned revisions. Defaults: CUDA in bf16 if
available (about 4.5 GB of GPU memory), else CPU in fp32 (slow, ~15 s per image: the larger backbone has 1.9B parameters).
Loading needs about 16 GB of system RAM.
"""
from __future__ import annotations
import argparse
import hashlib
import io
import json
import math
import os
import sys
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image, ImageCms, ImageOps
DEFAULT_REPO = "mesmertech/mesmer-ai-image-detector"
FILES = ("config.json", "policy.json", "fusion.json", "model.safetensors")
FP16_MAX = 65000.0
Image.MAX_IMAGE_PIXELS = 200_000_000 # refuse decompression bombs
_SRGB = ImageCms.createProfile("sRGB")
# ------------------------------------------------------------------------------------------------------------ decode
def to_srgb(im: Image.Image) -> Image.Image:
"""EXIF orientation, 16-bit / palette / alpha (on white) handling, ICC profile -> sRGB, 8-bit RGB."""
try:
im = ImageOps.exif_transpose(im)
except Exception: # noqa: BLE001
pass
icc = im.info.get("icc_profile")
if im.mode in ("I;16", "I;16B", "I;16L", "I", "F"):
a = np.asarray(im, dtype=np.float32)
a = a / (65535.0 if a.max() > 255 else 255.0) * 255.0
im = Image.fromarray(np.clip(a + 0.5, 0, 255).astype(np.uint8), "L")
if im.mode == "P":
im = im.convert("RGBA")
if im.mode in ("RGBA", "LA", "PA") or (im.mode in ("RGB", "L") and "transparency" in im.info):
im = im.convert("RGBA")
im = Image.alpha_composite(Image.new("RGBA", im.size, (255, 255, 255, 255)), im).convert("RGB")
if icc:
try:
src = ImageCms.ImageCmsProfile(io.BytesIO(icc))
im = ImageCms.profileToProfile(im, src, _SRGB, outputMode="RGB", renderingIntent=ImageCms.Intent.PERCEPTUAL)
except Exception: # noqa: BLE001
pass
if im.mode != "RGB":
im = im.convert("RGB")
return im
def load_pixels(image) -> np.ndarray:
"""A path, bytes, a PIL image or an H x W x 3 uint8 RGB array -> H x W x 3 uint8 sRGB pixels."""
if isinstance(image, np.ndarray):
if image.dtype != np.uint8 or image.ndim != 3 or image.shape[2] != 3:
raise ValueError("arrays must be H x W x 3 uint8 RGB")
return np.ascontiguousarray(image)
if isinstance(image, Image.Image):
im = image
elif isinstance(image, (bytes, bytearray, memoryview)):
im = Image.open(io.BytesIO(image))
else:
im = Image.open(os.fspath(image))
im.load()
return np.asarray(to_srgb(im), dtype=np.uint8).copy()
# ------------------------------------------------------------------------------------------------------------ views
def cap_long_side(px: np.ndarray, max_side: int) -> np.ndarray:
"""Downscale so the long side == max_side (PIL LANCZOS), only when it is larger; max_side <= 0 = off."""
h, w = px.shape[:2]
if max_side <= 0 or max(h, w) <= max_side:
return px
k = max_side / max(h, w)
nw, nh = (max_side, max(1, round(h * k))) if w >= h else (max(1, round(w * k)), max_side)
return np.asarray(Image.fromarray(px).resize((nw, nh), Image.LANCZOS), dtype=np.uint8)
def view_resize_crop(im: Image.Image, S: int) -> Image.Image:
"""View A: short side -> S (bicubic), centre S x S crop."""
s = S / min(im.size)
im = im.resize((max(S, round(im.width * s)), max(S, round(im.height * s))), Image.Resampling.BICUBIC, reducing_gap=None)
x, y = (im.width - S) // 2, (im.height - S) // 2
return im.crop((x, y, x + S, y + S))
def _upscale_short(im: Image.Image, S: int) -> Image.Image:
if min(im.size) < S:
s = S / min(im.size)
im = im.resize((max(S, round(im.width * s)), max(S, round(im.height * s))), Image.Resampling.BICUBIC)
return im
def view_native_centre(im: Image.Image, S: int) -> Image.Image:
"""View Bc: native-pixel centre S x S crop (bicubic upscale first if the short side < S)."""
im = _upscale_short(im, S)
x, y = (im.width - S) // 2, (im.height - S) // 2
return im.crop((x, y, x + S, y + S))
def spread_crops(im: Image.Image, S: int, ts=(0.0, 0.25, 1.0)) -> list:
"""Native S x S crops centred on the short axis at long-axis fractions ts."""
im = _upscale_short(im, S)
W, H = im.size
out = []
for t in ts:
x, y = (round(t * (W - S)), (H - S) // 2) if W >= H else ((W - S) // 2, round(t * (H - S)))
out.append(np.asarray(im.crop((x, y, x + S, y + S)), np.uint8))
return out
# ------------------------------------------------------------------------------------------------------------ fusion
def rank_normalise(scores, ref_real_scores):
"""logit of the mid-rank ECDF of the reference real scores (clamped) + 1e-3 x the robust z-score."""
ref = np.sort(np.asarray(ref_real_scores, np.float64))
x = np.asarray(scores, np.float64)
n = len(ref)
u = (np.searchsorted(ref, x, "left") + np.searchsorted(ref, x, "right")) / 2.0
u = np.clip((u + 0.5) / (n + 1), 0.5 / (n + 1), 1 - 0.5 / (n + 1))
med = np.median(ref)
iqr = max(np.subtract(*np.percentile(ref, [75, 25])), 1e-12)
return np.log(u / (1 - u)) + 1e-3 * (x - med) / iqr
def display_p(score: float, t_unc: float, t_ai: float) -> float:
return 1.0 / (1.0 + math.exp(-max(-60.0, min(60.0, math.log(9.0) * (score - t_unc) / (t_ai - t_unc)))))
# ------------------------------------------------------------------------------------------------------------ model
class LoraLinear(nn.Module):
"""LoRA on a frozen Linear (dropout 0): base(x) + B(A(x)) * scaling, A/B kept in fp32."""
def __init__(self, base: nn.Linear, A: torch.Tensor, B: torch.Tensor, scaling: float):
super().__init__()
self.base, self.scaling = base, scaling
self.register_buffer("A", A)
self.register_buffer("B", B)
@property
def weight(self):
return self.base.weight
def forward(self, x):
result = self.base(x)
dt = result.dtype
xa = x.to(self.A.dtype) if x.dtype != self.A.dtype else x
result = result + F.linear(F.linear(xa, self.A), self.B) * self.scaling
return result.to(dt)
def _sha256(path, chunk=1 << 24):
h = hashlib.sha256()
with open(path, "rb") as f:
while b := f.read(chunk):
h.update(b)
return h.hexdigest()
def _backbone(spec: dict, cache_dir=None, verify=False):
import timm
from huggingface_hub import hf_hub_download
path = hf_hub_download(spec["hf_repo"], spec["file"], revision=spec["revision"], cache_dir=cache_dir)
if os.path.getsize(path) != spec["bytes"] or (verify and _sha256(path) != spec["sha256"]):
raise RuntimeError(f"{spec['hf_repo']}@{spec['revision']}: file does not match the pinned size / sha256")
m = timm.create_model(spec["timm_name"], pretrained=True, pretrained_cfg_overlay=dict(file=path), **spec["timm_kwargs"])
assert tuple(m.pretrained_cfg["mean"]) == (0.5, 0.5, 0.5) and tuple(m.pretrained_cfg["std"]) == (0.5, 0.5, 0.5)
return m
class Detector:
"""Two members on Perception Encoder backbones, scores rank-normalised and combined (0.6 PE-L + 0.4 PE-G)."""
def __init__(self, model_dir, device=None, precision=None, cache_dir=None, verify_backbones=False):
from safetensors.torch import load_file
d = os.fspath(model_dir)
self.cfg = json.load(open(os.path.join(d, "config.json")))
self.policy = json.load(open(os.path.join(d, "policy.json")))
fusion = json.load(open(os.path.join(d, "fusion.json")))
self.device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
self.precision = precision or ("bf16" if self.device.type == "cuda" else "fp32")
if self.precision not in ("bf16", "fp32"):
raise ValueError("precision must be bf16 or fp32")
self.bf16 = self.precision == "bf16"
torch.backends.cudnn.benchmark = False
W = load_file(os.path.join(d, self.cfg["weights_file"]))
mp, mg = self.cfg["members"]["pel"], self.cfg["members"]["peg"]
self.S_pel, self.S_peg = mp["S"], mg["S"]
self.cap_pel = int(mp.get("max_side") or 0)
# PE-L: final norm removed, attention pooling unused; bf16 base (as scored), LoRA applied unmerged at run time
pel = _backbone(self.cfg["backbones"]["pel"], cache_dir, verify_backbones)
pel.norm = nn.Identity()
pel.attn_pool = None
pel.requires_grad_(False)
pel.to(dtype=torch.bfloat16)
# PE-G: frozen, whole model bf16
peg = _backbone(self.cfg["backbones"]["peg"], cache_dir, verify_backbones)
peg.requires_grad_(False)
peg.to(dtype=torch.bfloat16)
if not self.bf16: # fp32 compute on the same bf16-rounded weights
pel.float()
peg.float()
pel.to(self.device)
peg.to(self.device)
lo = mp["lora"]
for i, blk in enumerate(pel.blocks):
for nm in ("qkv", "proj"):
A = W[f"pel.lora.blocks.{i}.attn.{nm}.lora_A.weight"].float().to(self.device)
B = W[f"pel.lora.blocks.{i}.attn.{nm}.lora_B.weight"].float().to(self.device)
setattr(blk.attn, nm, LoraLinear(getattr(blk.attn, nm), A, B, float(lo["scaling"])))
assert sum(isinstance(m, LoraLinear) for m in pel.modules()) == 2 * len(pel.blocks) == 2 * lo["blocks"]
self.pel, self.peg = pel.eval(), peg.eval()
self.H = {k: v.float().to(self.device) for k, v in W.items() if not k.startswith("pel.lora.")}
self.ref = {k: np.asarray(fusion["reference"][k], np.float64) for k in ("pel", "peg")}
self.w = fusion["weights"]
self.peg_layers, self.peg_keys, self.peg_dims = mg["layers"], mg["feat_keys"], mg["dims"]
self._hooks = {}
for L_ in self.peg_layers:
self.peg.blocks[L_ - 1].register_forward_hook(self._hook(L_))
self.mean = torch.tensor(mp["mean"], device=self.device).view(1, 3, 1, 1)
self.std = torch.tensor(mp["std"], device=self.device).view(1, 3, 1, 1)
@classmethod
def from_pretrained(cls, repo_or_dir: str = DEFAULT_REPO, revision=None, token=None, device=None, precision=None,
cache_dir=None, verify_backbones=False):
"""A local folder with this repo's files, or a Hub repo id (downloads config.json, policy.json, fusion.json and
model.safetensors)."""
if os.path.isdir(repo_or_dir):
d = repo_or_dir
else:
from huggingface_hub import snapshot_download
d = snapshot_download(repo_or_dir, revision=revision, token=token, cache_dir=cache_dir, allow_patterns=list(FILES))
return cls(d, device=device, precision=precision, cache_dir=cache_dir, verify_backbones=verify_backbones)
def _hook(self, L_):
def f(_m, _i, o):
self._hooks[L_] = o[0] if isinstance(o, tuple) else o
return f
# -------------------------------------------------------------------------------------------------------- views
def views(self, px: np.ndarray):
"""The PE-G view (448 resize + centre crop of the image as is) and the 5 PE-L views (from the image capped at a
1024 px long side): A = 336 resize + centre crop, Bc = native centre crop, 3 native crops spread along the long side."""
cap_l = cap_long_side(px, self.cap_pel)
pre_l = Image.fromarray(cap_l)
pre_g = pre_l if cap_l is px else Image.fromarray(px)
peg_v = np.array(view_resize_crop(pre_g, self.S_peg), np.uint8)
pel_v = [np.asarray(view_resize_crop(pre_l, self.S_pel), np.uint8),
np.asarray(view_native_centre(pre_l, self.S_pel), np.uint8)] + spread_crops(pre_l, self.S_pel)
return peg_v, np.stack(pel_v)
# -------------------------------------------------------------------------------------------------------- members
@torch.inference_mode()
def pel_logits(self, views: np.ndarray):
"""(N, S, S, 3) uint8 views -> per-view (main, anchor) logits."""
x = torch.from_numpy(views).to(self.device).permute(0, 3, 1, 2).contiguous()
x = (x.float() / 255.0 - self.mean) / self.std
with torch.autocast(device_type=self.device.type, dtype=torch.bfloat16, enabled=self.bf16):
t = self.pel.forward_features(x)
f = torch.cat([t[:, 0], t[:, 1:].mean(1)], 1).float()
H = self.H
z = f / f.norm(dim=1, keepdim=True).clamp_min(1e-12)
z = (z - H["pel.anchor.mu"]) / H["pel.anchor.sd"]
main = F.linear(z, H["pel.head.w"].view(1, -1), H["pel.head.b"]).squeeze(1)
anc = z @ H["pel.anchor.w"] + H["pel.anchor.b"]
return main.float().cpu().numpy(), anc.float().cpu().numpy()
def score_pel(self, v5: np.ndarray) -> dict:
m, a = self.pel_logits(v5)
return {"logit": float(m.mean()), "views": [float(v) for v in m], "anchor_logit": float(a.mean())}
@torch.inference_mode()
def score_peg(self, v: np.ndarray) -> dict:
x = torch.from_numpy(v[None]).to(self.device).permute(0, 3, 1, 2).float().div_(255)
x = (x - self.mean) / self.std
if self.bf16:
x = x.to(torch.bfloat16)
self._hooks.clear()
f = self.peg.forward_features(x)
res = {"pooled": self.peg.forward_head(f).float()}
for L_ in self.peg_layers:
p = self._hooks[L_].float()
res[f"L{L_}_mean"] = p.mean(1)
res[f"L{L_}_std"] = p.std(1, unbiased=False)
X = torch.cat([res[k].clamp(-FP16_MAX, FP16_MAX).half().float() for k in self.peg_keys], 1)
X = torch.nan_to_num(X, nan=0.0, posinf=65504.0, neginf=-65504.0)
a = 0
for d in self.peg_dims:
X[:, a:a + d] /= X[:, a:a + d].norm(dim=1, keepdim=True).clamp_min(1e-12)
a += d
H = self.H
X = (X - H["peg.lr.mu"]) / H["peg.lr.sd"]
return {"logit": float((X @ H["peg.lr.w"] + H["peg.lr.b"]).item())}
# -------------------------------------------------------------------------------------------------------- score
def combine(self, pel: dict, peg: dict) -> dict:
zp = float(rank_normalise(np.array([pel["logit"]], np.float64), self.ref["pel"])[0])
zg = float(rank_normalise(np.array([peg["logit"]], np.float64), self.ref["peg"])[0])
w = self.w
z = (zp + zg) / 2 if w["pel"] == w["peg"] else (w["pel"] * zp + w["peg"] * zg) / (w["pel"] + w["peg"])
th = self.policy["thresholds"]
t_ai, t_unc = th["likely_ai_at_or_above"], th["uncertain_at_or_above"]
verdict = "likely_ai" if z >= t_ai else ("uncertain" if z >= t_unc else "likely_real")
return {"verdict": verdict, "score": z, "p_ai": display_p(z, t_unc, t_ai), "thresholds": dict(th),
"members": {"pel": {"logit": pel["logit"], "z": zp, "view_logits": dict(zip(("A", "Bc", "spread0", "spread0.25", "spread1"),
pel["views"])),
"anchor_logit": pel["anchor_logit"]},
"peg": {"logit": peg["logit"], "z": zg}}}
def predict_pixels(self, px: np.ndarray) -> dict:
peg_v, pel_v = self.views(px)
out = self.combine(self.score_pel(pel_v), self.score_peg(peg_v))
out["image"] = {"width": int(px.shape[1]), "height": int(px.shape[0])}
return out
def predict(self, image) -> dict:
"""Score one image: a path, bytes, a PIL image or an H x W x 3 uint8 RGB array."""
return self.predict_pixels(load_pixels(image))
# -------------------------------------------------------------------------------------------------------- heatmap
@staticmethod
def grid(W, H, S, overlap=0.5, min_crops=16, max_crops=64, min_stride=24):
step = S * (1.0 - overlap)
nx = 1 if W == S else math.ceil((W - S) / step) + 1
ny = 1 if H == S else math.ceil((H - S) / step) + 1
mx, my = max(nx, (W - S) // min_stride + 1), max(ny, (H - S) // min_stride + 1)
while nx * ny < min_crops and (nx < mx or ny < my):
if ((W - S) / nx >= (H - S) / ny and nx < mx) or ny >= my:
nx += 1
else:
ny += 1
while nx * ny > max_crops:
if nx >= ny:
nx -= 1
else:
ny -= 1
xs = [round(i * (W - S) / (nx - 1)) for i in range(nx)] if nx > 1 else [(W - S) // 2]
ys = [round(j * (H - S) / (ny - 1)) for j in range(ny)] if ny > 1 else [(H - S) // 2]
return xs, ys
def heatmap(self, image) -> dict:
"""Experimental: native 336 x 336 crops over the image (capped at a 1024 px long side), each scored by the PE-L
member. Never changes the image-level score or verdict. Boxes are in original-image pixels [x0, y0, x1, y1]."""
px = load_pixels(image)
hp = self.policy["heatmap"]
S = self.S_pel
H0, W0 = px.shape[:2]
im = _upscale_short(Image.fromarray(cap_long_side(px, int(hp.get("max_side", 1024) or 0))), S)
W, H = im.size
sx, sy = W / W0, H / H0
xs, ys = self.grid(W, H, S, hp["overlap"], hp["min_crops"], hp["max_crops"], hp["min_stride_px"])
crops = np.stack([np.asarray(im.crop((x, y, x + S, y + S)), np.uint8) for y in ys for x in xs])
bs = int(hp.get("batch", 32))
logits = np.concatenate([self.pel_logits(crops[i:i + bs])[0] for i in range(0, len(crops), bs)])
th = hp["crop_thresholds"]
c_ai, c_unc = th["likely_ai_at_or_above"], th["uncertain_at_or_above"]
L = logits.reshape(len(ys), len(xs))
return {"experimental": True, "nx": len(xs), "ny": len(ys),
"boxes": [[x / sx, y / sy, (x + S) / sx, (y + S) / sy] for y in ys for x in xs],
"logits": L.tolist(), "p_display": [[display_p(float(v), c_unc, c_ai) for v in row] for row in L],
"crop_thresholds": dict(th), "frac_likely_ai": float((logits >= c_ai).mean()),
"order": "row-major (y, then x)"}
# ------------------------------------------------------------------------------------------------------------ CLI
def main(argv=None):
ap = argparse.ArgumentParser(description="Mesmer AI Image Detector: is this image AI-generated?")
ap.add_argument("images", nargs="+", help="image files (JPEG, PNG, WebP, GIF, BMP, TIFF, AVIF)")
ap.add_argument("--model", default=DEFAULT_REPO, help=f"Hub repo id or local folder (default {DEFAULT_REPO})")
ap.add_argument("--revision", default=None)
ap.add_argument("--device", default=None, help="cuda / cpu (default: cuda if available)")
ap.add_argument("--precision", choices=["bf16", "fp32"], default=None, help="default: bf16 on cuda, fp32 on cpu")
ap.add_argument("--json", action="store_true", help="print one JSON object per image")
ap.add_argument("--heatmap", action="store_true", help="add the experimental crop map (implies --json)")
ap.add_argument("--verify-backbones", action="store_true", help="sha256-check the downloaded backbone files")
a = ap.parse_args(argv)
det = Detector.from_pretrained(a.model, revision=a.revision, device=a.device, precision=a.precision,
verify_backbones=a.verify_backbones)
for f in a.images:
try:
px = load_pixels(f)
r = det.predict_pixels(px)
if a.heatmap:
r["heatmap"] = det.heatmap(px)
except Exception as e: # noqa: BLE001
r = {"error": f"{type(e).__name__}: {e}"}
if a.json or a.heatmap:
print(json.dumps({"file": f, **r}), flush=True)
elif "error" in r:
print(f"{f}\terror\t{r['error']}", flush=True)
else:
print(f"{f}\t{r['verdict']}\tscore {r['score']:.3f}\tp_ai {r['p_ai']:.3f}", flush=True)
if __name__ == "__main__":
sys.exit(main())