Thatcher_Effect_Faces / quickstart_snippet.py
zer0int's picture
Upload 3 files
7c881b4 verified
Raw History Blame Contribute Delete
6.03 kB
# CLIP vs SigLIP 2 Large vs DINOv2 Large on FFHQ and SFHQ.
# Install: pip install -U torch transformers datasets pillow
from itertools import islice
from io import BytesIO
from math import acos, pi
from pathlib import Path
from statistics import fmean, stdev
import torch
import torch.nn.functional as F
from datasets import Image as HFImage, load_dataset
from PIL import Image
from transformers import AutoImageProcessor, AutoProcessor, CLIPModel, Dinov2Model, SiglipVisionModel
REPO = "zer0int/Thatcher_Effect_Faces" # HF ID by default; also accepts a local export folder.
N = 49 # 49 = Full-Thatcher ('both') quartets from each dataset's original root.
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
MODELS = [
("CLIP ViT-L/14", "openai/clip-vit-large-patch14", "clip"),
("SigLIP 2 Large", "google/siglip2-large-patch16-256", "siglip2"),
("DINOv2 Large", "facebook/dinov2-large", "dino"),
]
class SiglipImageOnly(SiglipVisionModel):
# ignore unused text tower and contrastive logits that are unexpected
# when loading the vision tower from a joint SigLIP checkpoint.
_keys_to_ignore_on_load_unexpected = set(
SiglipVisionModel._keys_to_ignore_on_load_unexpected or ()
) | {r"^text_model\.", r"^logit_scale$", r"^logit_bias$"}
def decode_rgb(image_value):
if isinstance(image_value, Image.Image):
return image_value.convert("RGB")
if isinstance(image_value, dict):
if image_value.get("bytes") is not None:
with Image.open(BytesIO(image_value["bytes"])) as image:
return image.convert("RGB")
if image_value.get("path") and Path(image_value["path"]).is_file():
with Image.open(image_value["path"]) as image:
return image.convert("RGB")
raise TypeError(f"Unsupported image format: {type(image_value).__name__}")
def summarize(upright, inverted):
"""Summarize paired faces, keeping model distances distinct from human accuracy."""
excesses = [i - u for u, i in zip(upright, inverted)]
n = len(excesses)
if not n:
raise ValueError("Cannot summarize an empty set of Thatcher quartets")
# angular distance / 180 degrees as a genuine bounded percentage.
# report the *paired* upright-minus-inverted angular distance in pp.
angular_excess_pp = fmean(
100.0 / pi * (acos(max(-1., min(1., u))) - acos(max(-1., min(1., i))))
for u, i in zip(upright, inverted)
)
# % of face quartets where inversion makes normal and Thatcher MORE similar.
favorable_pct = 100.0 * sum(e > 0 for e in excesses) / n
# face-to-face consistency
spread = stdev(excesses) if n > 1 else 0.0
d_faces = fmean(excesses) / spread if spread > 0 else float("nan")
return fmean(upright), fmean(inverted), fmean(excesses), angular_excess_pp, favorable_pct, d_faces, n
rows_by_source = {}
for source in ("ffhq", "sfhq"):
if Path(REPO).is_dir():
shards = sorted((Path(REPO) / "data" / source / "original").glob("*.parquet"))
if not shards:
raise FileNotFoundError(f"No {source} Parquet files in {REPO}")
ds = load_dataset("parquet", data_files={"train": [str(p) for p in shards]},
split="train", streaming=False)
else:
ds = load_dataset(REPO, f"{source}_original", split="train", streaming=False)
# .decode(False) is for IterableDataset, not a cached Dataset.
# Disable automatic image decoding using the Dataset.cast_column API.
for column in ("normal_u", "normal_i", "thatcher_u", "thatcher_i"):
if isinstance(ds.features[column], HFImage):
ds = ds.cast_column(column, HFImage(decode=False))
rows_by_source[source] = list(islice((r for r in ds if r["face_variant"] == "both"), N))
if not rows_by_source[source]:
raise RuntimeError(f"Empty dataset config: {source}_original")
scores = {source: {} for source in rows_by_source}
for label, checkpoint, family in MODELS:
# SigLIP's vision-only class bypasses the upstream text-config
processor_cls = AutoProcessor if family == "clip" else AutoImageProcessor
model_cls = {"clip": CLIPModel, "siglip2": SiglipImageOnly, "dino": Dinov2Model}[family]
processor = processor_cls.from_pretrained(checkpoint)
model = model_cls.from_pretrained(checkpoint).to(DEVICE).eval().float()
for source, rows in rows_by_source.items():
upright, inverted = [], []
for row in rows:
images = [decode_rgb(row[k]) for k in ("normal_u", "normal_i", "thatcher_u", "thatcher_i")]
batch = {k: v.to(DEVICE) for k, v in processor(images=images, return_tensors="pt").items()}
with torch.inference_mode():
if family == "dino":
z = model(**batch).last_hidden_state[:, 0, :]
elif family == "siglip2":
z = model(**batch).pooler_output
else:
z = model.get_image_features(**batch)
if not isinstance(z, torch.Tensor):
z = (getattr(z, "image_embeds", None)
if getattr(z, "image_embeds", None) is not None
else z.pooler_output)
z = F.normalize(z.float(), dim=-1)
upright.append((z[0] * z[2]).sum().item())
inverted.append((z[1] * z[3]).sum().item())
scores[source][label] = summarize(upright, inverted)
del model
if DEVICE == "cuda":
torch.cuda.empty_cache()
for source in ("ffhq", "sfhq"):
print(f"\n{source.upper()} — original root, full Thatcher, {len(rows_by_source[source])} quartets")
print(f"{'Model':20} {'N':>3} {'upright':>9} {'inverted':>9} {'cos excess':>10} {'ang pp':>8} {'% faces':>8} {'d_faces':>8}")
for label, _, _ in MODELS:
u, i, excess, ang_pp, favorable, d_faces, n = scores[source][label]
print(f"{label:20} {n:3d} {u:9.4f} {i:9.4f} {excess:+10.4f} {ang_pp:+8.2f} {favorable:8.1f} {d_faces:8.2f}")