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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
#!/usr/bin/env python3
"""
Full Thatcher benchmark: CLIP ViT-L/14, SigLIP 2 Large, and DINOv2 Large.
By default, evaluates FFHQ + SFHQ, all four image roots, and ALL available
face variants (both/eo/mo plus ll/rr in gazefix roots).
Resumes completed quartet/model results from an existing CSV.

Install: pip install -U torch transformers datasets pillow
Run:     python getting_started.py
Preview: python getting_started.py --preflight-only  (also caches the dataset)
Quick:   python getting_started.py --model clip --max-per-variant 2 --fresh

Dataset partitions are downloaded and cached before GPU inference; subsequent
runs reuse the Hugging Face Hub / Datasets caches (HF_HOME, HF_HUB_CACHE,
HF_DATASETS_CACHE). No dataset streaming is used.
"""

from __future__ import annotations

import argparse
import csv
import hashlib
import io
import statistics
from collections import Counter, defaultdict
from math import acos, pi
from pathlib import Path

MODELS = {
    "CLIP ViT-L/14": "openai/clip-vit-large-patch14",
    "SigLIP 2 Large": "google/siglip2-large-patch16-256",
    "DINOv2 Large": "facebook/dinov2-large",
}
MODEL_SHORT = {
    "clip": "CLIP ViT-L/14",
    "siglip2": "SigLIP 2 Large",
    "dino": "DINOv2 Large",
}
ROOT_VARIANTS = ("original", "gazefix", "passportify", "passportify_gazefix")
BASE_VARIANTS = ("both", "eo", "mo")
MIRROR_VARIANTS = ("ll", "rr")
IMAGE_COLS = ("normal_u", "normal_i", "thatcher_u", "thatcher_i")
FIELDS = (
    "dataset_ref", "source_dataset", "root_variant", "face_variant",
    "identity", "model", "model_id", "cos_upright", "cos_inverted",
    "thatcher_excess", "angular_excess_pp",
)
SUMMARY_FIELDS = (
    "source_dataset", "root_variant", "face_variant", "model", "N",
    "cos_upright", "cos_inverted", "thatcher_excess",
    "angular_excess_pp", "pct_faces", "d_faces",
)


def expected_variants(root_variant):
    # LL/RR were generated only for the two gaze-corrected roots.
    return BASE_VARIANTS + (MIRROR_VARIANTS if "gazefix" in root_variant else ())


def decode_rgb(image_value):
    from PIL import Image

    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(io.BytesIO(image_value["bytes"])) as image:
                return image.convert("RGB")
        if image_value.get("path"):
            with Image.open(image_value["path"]) as image:
                return image.convert("RGB")
    raise TypeError(f"Unsupported image column: {type(image_value).__name__}")


def angular_distance_percent(cosine):
    """Angular distance as a percentage of the entire 180-degree range."""
    return 100.0 * acos(max(-1.0, min(1.0, cosine))) / pi


def dataset_ref(args):
    local_root = args.local_root or (
        Path(args.repo) if Path(args.repo).is_dir() else None
    )
    if local_root is None:
        return f"hub:{args.repo}"
    # CSV resume marker
    digest = hashlib.sha256(str(local_root.resolve()).encode("utf-8")).hexdigest()[:16]
    return f"local:{digest}"


def load_examples(args, source, root_variant):
    """Download/prepare once, then return a locally cached Arrow dataset."""
    from datasets import Image, load_dataset

    dataset_cache_dir = (
        str(args.dataset_cache_dir) if args.dataset_cache_dir is not None else None
    )
    local_root = args.local_root or (
        Path(args.repo) if Path(args.repo).is_dir() else None
    )
    if local_root is not None:
        folder = local_root / "data" / source / root_variant
        parquet_paths = sorted(folder.glob("*.parquet"))
        if not parquet_paths:
            raise FileNotFoundError(f"No Parquet shards under {folder}")
        ds = load_dataset(
            "parquet",
            data_files={"train": [str(path) for path in parquet_paths]},
            split="train",
            streaming=False,
            cache_dir=dataset_cache_dir,
        )
    else:
        ds = load_dataset(
            args.repo, name=f"{source}_{root_variant}",
            split="train", streaming=False, cache_dir=dataset_cache_dir,
        )

    # FIX: Dataset has no .decode(False); that API is for IterableDataset.
    # Cast the image features instead, so only selected quartets are decoded
    # by decode_rgb() during GPU inference.
    for column in IMAGE_COLS:
        if isinstance(ds.features[column], Image):
            ds = ds.cast_column(column, Image(decode=False))
    return ds


def preflight_coverage(args, sources, roots, example_sets, example_indices):
    """Cache partitions and index metadata without loading image bytes."""
    coverage = {}
    total = 0
    for source in sources:
        for root_variant in roots:
            available = expected_variants(root_variant)
            wanted = (
                available if args.face_variant == "all"
                else tuple(v for v in available if v == args.face_variant)
            )
            if not wanted:
                continue  # E.g., --face-variant ll on the original root.
            print(f"Preparing cached dataset: {source}/{root_variant}", flush=True)
            example_sets[(source, root_variant)] = load_examples(
                args, source, root_variant
            )
            counts = Counter()
            identity_sets = defaultdict(set)
            selected_indices = []
            # Select only two metadata columns: no image bytes hit Python here.
            metadata = example_sets[(source, root_variant)].select_columns(
                ["face_variant", "identity"]
            )
            for row_index, row in enumerate(metadata):
                variant = str(row["face_variant"]).lower()
                if variant not in available:
                    raise ValueError(
                        f"Unexpected face_variant={variant!r} in {source}/{root_variant}"
                    )
                if variant not in wanted:
                    continue
                if args.max_per_variant and counts[variant] >= args.max_per_variant:
                    continue
                identity = str(row["identity"])
                if identity in identity_sets[variant]:
                    raise ValueError(
                        f"Duplicate identity {identity!r}: {source}/{root_variant}/{variant}"
                    )
                identity_sets[variant].add(identity)
                counts[variant] += 1
                selected_indices.append((variant, identity, row_index))

            missing = [variant for variant in wanted if not counts[variant]]
            if missing:
                raise RuntimeError(
                    f"Missing conditions {missing}: {source}/{root_variant}"
                )
            if not args.max_per_variant and len(wanted) > 1:
                first_ids = identity_sets[wanted[0]]
                for variant in wanted[1:]:
                    if identity_sets[variant] != first_ids:
                        raise RuntimeError(
                            f"Different identity sets in {source}/{root_variant}: "
                            f"{wanted[0]} vs {variant}"
                        )
            coverage[(source, root_variant)] = {
                variant: frozenset(identity_sets[variant]) for variant in wanted
            }
            example_indices[(source, root_variant)] = selected_indices
            n = sum(counts.values())
            total += n
            print(f"{source.upper():4} / {root_variant:20}: {dict(counts)}", flush=True)
    if not coverage:
        raise RuntimeError("No matching source/root/face conditions selected")
    model_count = len(MODELS) if args.model == "all" else 1
    print(
        f"Coverage: {total} quartets per model "
        f"({total * model_count} across {model_count} selected model(s); "
        "four images each).\n",
        flush=True,
    )
    return coverage


def result_key(row):
    return tuple(str(row[name]) for name in (
        "dataset_ref", "source_dataset", "root_variant",
        "face_variant", "identity", "model_id",
    ))


def load_existing(out, fresh):
    if fresh or not out.is_file() or out.stat().st_size == 0:
        return {}
    existing = {}
    with out.open("r", newline="", encoding="utf-8-sig") as file:
        reader = csv.DictReader(file)
        if tuple(reader.fieldnames or ()) != FIELDS:
            raise RuntimeError(
                f"Existing CSV has a different schema: {out}. "
                "Use --out NEW_FILE or --fresh to start a new benchmark."
            )
        for row in reader:
            if any(row.get(field) is None for field in FIELDS):
                raise RuntimeError(f"Incomplete CSV row in {out}; inspect before resuming")
            key = result_key(row)
            if key in existing:
                raise RuntimeError(f"Duplicate checkpoint key in {out}: {key}")
            existing[key] = row
    return existing


def load_model(model_name, cache_dir, device):
    import torch
    from transformers import (
        AutoImageProcessor, AutoProcessor, CLIPModel, Dinov2Model,
        SiglipVisionModel,
    )

    cache_kwargs = {"cache_dir": str(cache_dir)} if cache_dir is not None else {}
    if model_name.startswith("openai/clip"):
        processor = AutoProcessor.from_pretrained(model_name, **cache_kwargs)
        model = CLIPModel.from_pretrained(model_name, **cache_kwargs)
        family = "clip"
    elif "siglip2" in model_name:
        # The published SigLIP 2 Large checkpoint uses the SigLIP vision
        # architecture. Loading only it avoids unused text-config defaults.
        class SiglipImageOnly(SiglipVisionModel):
            # Ignore unused keys
            _keys_to_ignore_on_load_unexpected = set(
                SiglipVisionModel._keys_to_ignore_on_load_unexpected or ()
            ) | {r"^text_model\.", r"^logit_scale$", r"^logit_bias$"}

        processor = AutoImageProcessor.from_pretrained(model_name, **cache_kwargs)
        model = SiglipImageOnly.from_pretrained(model_name, **cache_kwargs)
        family = "siglip2"
    else:
        processor = AutoImageProcessor.from_pretrained(model_name, **cache_kwargs)
        model = Dinov2Model.from_pretrained(model_name, **cache_kwargs)
        family = "dino"
    model = model.to(device).eval().float()
    return model, processor, family


def image_embeddings(model, processor, family, row, device):
    """Compute a complete normal/Thatcher upright/inverted quartet."""
    import torch
    import torch.nn.functional as F

    images = [decode_rgb(row[column]) for column in IMAGE_COLS]
    batch = processor(images=images, return_tensors="pt")
    batch = {key: value.to(device) for key, value in batch.items() if hasattr(value, "to")}
    with torch.inference_mode():
        if family == "dino":
            z = model(**batch).last_hidden_state[:, 0, :]
        elif family == "siglip2":
            # Same pooled visual embedding as SiglipModel.get_image_features().
            z = model(**batch).pooler_output
        else:
            z = model.get_image_features(**batch)
            if not isinstance(z, torch.Tensor):
                if getattr(z, "image_embeds", None) is not None:
                    z = z.image_embeds
                elif getattr(z, "pooler_output", None) is not None:
                    z = z.pooler_output
                else:
                    z = z[0]
        z = F.normalize(z.float(), dim=-1).cpu()
    if z.ndim != 2 or z.shape[0] != 4:
        raise RuntimeError(f"Expected four embeddings; got {tuple(z.shape)}")
    return float((z[0] * z[2]).sum()), float((z[1] * z[3]).sum())


def summarize(vals, source, root_variant, face_variant, model):
    upright = [float(row["cos_upright"]) for row in vals]
    inverted = [float(row["cos_inverted"]) for row in vals]
    excesses = [float(row["thatcher_excess"]) for row in vals]
    spread = statistics.stdev(excesses) if len(excesses) > 1 else 0.0
    return {
        "source_dataset": source,
        "root_variant": root_variant,
        "face_variant": face_variant,
        "model": model,
        "N": len(vals),
        "cos_upright": statistics.fmean(upright),
        "cos_inverted": statistics.fmean(inverted),
        "thatcher_excess": statistics.fmean(excesses),
        "angular_excess_pp": statistics.fmean(
            float(row["angular_excess_pp"]) for row in vals
        ),
        "pct_faces": 100.0 * sum(delta > 0 for delta in excesses) / len(excesses),
        "d_faces": (
            statistics.fmean(excesses) / spread if spread > 0 else float("nan")
        ),
    }


def write_summary(args, coverage, model_items, completed, current_ref):
    grouped = defaultdict(list)
    for (source, root_variant), variants in coverage.items():
        for face_variant, identities in variants.items():
            for model, model_id in model_items:
                for identity in identities:
                    key = (
                        current_ref, source, root_variant, face_variant,
                        identity, model_id,
                    )
                    if key not in completed:
                        raise RuntimeError(f"Missing result for {key}")
                    grouped[(source, root_variant, face_variant, model)].append(
                        completed[key]
                    )

    summary_rows = []
    for (source, root_variant), variants in coverage.items():
        print(f"\n{source.upper()} / {root_variant}")
        print(
            f"{'Model':20} {'Face':5} {'N':>3} "
            f"{'upright':>8} {'inverted':>8} {'excess':>9} "
            f"{'ang pp':>8} {'% faces':>8} {'d_faces':>8}"
        )
        for face_variant in expected_variants(root_variant):
            if face_variant not in variants:
                continue
            for model, _ in model_items:
                vals = grouped[(source, root_variant, face_variant, model)]
                row = summarize(vals, source, root_variant, face_variant, model)
                summary_rows.append(row)
                print(
                    f"{model:20} {face_variant:5} {row['N']:3d} "
                    f"{row['cos_upright']:8.4f} {row['cos_inverted']:8.4f} "
                    f"{row['thatcher_excess']:+9.4f} "
                    f"{row['angular_excess_pp']:+8.2f} "
                    f"{row['pct_faces']:8.1f} {row['d_faces']:8.2f}"
                )

    summary_out = (
        args.summary_out
        if args.summary_out is not None
        else args.out.with_name(f"{args.out.stem}_summary.csv")
    )
    summary_out.parent.mkdir(parents=True, exist_ok=True)
    with summary_out.open("w", newline="", encoding="utf-8-sig") as file:
        writer = csv.DictWriter(file, fieldnames=SUMMARY_FIELDS)
        writer.writeheader()
        writer.writerows(summary_rows)
    print(f"\nPer-quartet results: {args.out}")
    print(f"Complete summary:    {summary_out}")
    print("Cosine distributions are not calibrated across models.")
    print("Angular pp = paired extra angle / 180 deg * 100; % faces = positive excess rate.")
    print("d_faces = mean paired excess / sample SD across identities (not human accuracy).")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--repo", default="zer0int/Thatcher_Effect_Faces")
    parser.add_argument("--local-root", type=Path, help="Local FFHQ/SFHQ Parquet export")
    parser.add_argument("--source", choices=("both", "ffhq", "sfhq"), default="both")
    parser.add_argument(
        "--root-variant", choices=("all",) + ROOT_VARIANTS, default="all"
    )
    parser.add_argument(
        "--face-variant", choices=("all",) + BASE_VARIANTS + MIRROR_VARIANTS,
        default="all",
    )
    parser.add_argument(
        "--max-per-variant", type=int, default=0,
        help="0 (default) = all quartets; positive integer = quick sample per condition",
    )
    parser.add_argument(
        "--model", choices=("all",) + tuple(MODEL_SHORT), default="all"
    )
    parser.add_argument("--device", default="auto", help="auto, cuda, cpu, ...")
    parser.add_argument(
        "--cache-dir", type=Path,
        default=None,
        help="Optional model cache override (default: Hugging Face cache settings)",
    )
    parser.add_argument(
        "--dataset-cache-dir", type=Path, default=None,
        help="Optional Arrow cache override (default: HF_DATASETS_CACHE / HF_HOME)",
    )
    parser.add_argument("--out", type=Path, default=Path("thatcher_quickstart.csv"))
    parser.add_argument("--summary-out", type=Path, default=None)
    parser.add_argument("--fresh", action="store_true", help="Overwrite output CSV and recompute")
    parser.add_argument(
        "--preflight-only", action="store_true",
        help="Check variant/identity coverage without loading any models",
    )
    args = parser.parse_args()
    if args.max_per_variant < 0:
        parser.error("--max-per-variant must be >= 0")
    if args.out == args.summary_out:
        parser.error("--out and --summary-out must be different files")

    sources = ("ffhq", "sfhq") if args.source == "both" else (args.source,)
    roots = ROOT_VARIANTS if args.root_variant == "all" else (args.root_variant,)
    # Keep these memory-mapped datasets alive and reuse them for every model.
    example_sets = {}
    example_indices = {}
    coverage = preflight_coverage(args, sources, roots, example_sets, example_indices)
    if args.preflight_only:
        return

    import torch

    device = (
        "cuda" if torch.cuda.is_available() else "cpu"
    ) if args.device == "auto" else args.device
    if device.startswith("cuda") and not torch.cuda.is_available():
        raise RuntimeError("CUDA unavailable; use --device cpu or configure CUDA")
    if args.cache_dir is not None:
        args.cache_dir.mkdir(parents=True, exist_ok=True)
    args.out.parent.mkdir(parents=True, exist_ok=True)
    completed = load_existing(args.out, args.fresh)
    current_ref = dataset_ref(args)
    model_items = (
        list(MODELS.items()) if args.model == "all"
        else [(MODEL_SHORT[args.model], MODELS[MODEL_SHORT[args.model]])]
    )

    output_exists = args.out.is_file() and args.out.stat().st_size > 0 and not args.fresh
    with args.out.open("a" if output_exists else "w", newline="", encoding="utf-8") as file:
        writer = csv.DictWriter(file, fieldnames=FIELDS)
        if not output_exists:
            writer.writeheader()
            file.flush()

        for model_label, model_id in model_items:
            required = {
                (current_ref, source, root_variant, variant, identity, model_id)
                for (source, root_variant), variants in coverage.items()
                for variant, identities in variants.items()
                for identity in identities
            }
            missing = required - completed.keys()
            if not missing:
                print(f"SKIP {model_label}: all {len(required)} quartet results already saved.")
                continue

            print(f"\nLoading {model_label} on {device}; {len(missing)} remaining quartets...", flush=True)
            model, processor, family = load_model(model_id, args.cache_dir, device)
            done = 0
            try:
                for (source, root_variant), variants in coverage.items():
                    remaining = {
                        (variant, identity)
                        for variant, identities in variants.items()
                        for identity in identities
                        if (current_ref, source, root_variant, variant, identity, model_id)
                        not in completed
                    }
                    if not remaining:
                        continue
                    for variant, identity, row_index in example_indices[(source, root_variant)]:
                        if (variant, identity) not in remaining:
                            continue
                        # Fetch image bytes only for a quartet we actually need.
                        row = example_sets[(source, root_variant)][row_index]
                        cos_upright, cos_inverted = image_embeddings(
                            model, processor, family, row, device
                        )
                        result = {
                            "dataset_ref": current_ref,
                            "source_dataset": source,
                            "root_variant": root_variant,
                            "face_variant": variant,
                            "identity": identity,
                            "model": model_label,
                            "model_id": model_id,
                            "cos_upright": cos_upright,
                            "cos_inverted": cos_inverted,
                            "thatcher_excess": cos_inverted - cos_upright,
                            "angular_excess_pp": (
                                angular_distance_percent(cos_upright)
                                - angular_distance_percent(cos_inverted)
                            ),
                        }
                        writer.writerow(result)
                        file.flush()  # Per-quartet checkpoint: interruption-safe.
                        completed[result_key(result)] = result
                        remaining.remove((variant, identity))
                        done += 1
                        if done % 20 == 0:
                            print(f"  {model_label}: {done}/{len(missing)} new quartets", flush=True)
                        if not remaining:
                            break
                    if remaining:
                        raise RuntimeError(
                            f"Preflight/compute coverage mismatch for {source}/{root_variant}: "
                            f"{len(remaining)} quartets missing"
                        )
            finally:
                del model
                if device.startswith("cuda"):
                    torch.cuda.empty_cache()
            print(f"{model_label}: finished {done} new quartets.", flush=True)

    write_summary(args, coverage, model_items, completed, current_ref)


if __name__ == "__main__":
    main()