-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheval_harness.py
More file actions
2035 lines (1806 loc) · 90.5 KB
/
Copy patheval_harness.py
File metadata and controls
2035 lines (1806 loc) · 90.5 KB
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
eval_harness.py — ImageForge Eval Harness
==========================================
Drives the live FastAPI /generate endpoint, collects images, and computes
clean-FID + HPSv2 + GenEval2 (Soft-TIFA) for two model keys (base vs candidate).
Usage
-----
# Base vs base (noise floor, different seeds):
python eval_harness.py --base sd-turbo --candidate sd-turbo --noise-floor
# Base vs LoRA candidate:
python eval_harness.py --base sd-turbo --candidate sdxl-turbo
# Skip GenEval2 if Qwen3-VL is not available locally:
python eval_harness.py --base sd-turbo --candidate sdxl-turbo --skip-geneval
# Run FID+HPS only (fastest):
python eval_harness.py --base sd-turbo --candidate sdxl-turbo --skip-geneval
Requirements
------------
Install on the Mac (MPS box) — the serving environment:
pip install clean-fid hpsv2 httpx Pillow tqdm
GenEval2 (runs on CUDA box — Qwen3-VL-8B needs ~19 GB VRAM at FP16, ~5 GB at INT4):
git clone https://github.com/facebookresearch/GenEval2
cd GenEval2
pip install torch transformers==4.57.0 pillow tqdm scipy
# For INT4 on 4090: pip install bitsandbytes
# Copy geneval2_data.jsonl from the repo into this directory or pass --geneval2-data.
API
---
Drives http://127.0.0.1:8765/generate with GenerateRequest schema:
{
"prompt": str, "model": str|null, "steps": int|null, "guidance": float|null,
"width": int|null, "height": int|null, "seed": int,
"return_mode": "base64"
}
Response: GenerationResponse.image_base64 (PNG, base64).
Seeds are pinned per-prompt for reproducibility; noise-floor run uses seed+1 offsets.
The engine uses torch.Generator(device="cpu").manual_seed(seed) — deterministic across runs.
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import io
import json
import logging
import os
import shutil
import sys
import time
from pathlib import Path
from typing import Optional
# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-8s %(message)s",
datefmt="%H:%M:%S",
)
log = logging.getLogger("eval")
# ---------------------------------------------------------------------------
# Constants / thresholds
# ---------------------------------------------------------------------------
API_URL = "http://127.0.0.1:8765"
GENERATE_ENDPOINT = f"{API_URL}/generate"
# Optional X-API-Key sent with every request. The API's key gate is opt-in
# (app.py: auth_required defaults False), but once an operator turns it on,
# EVERY /generate call from this harness 401s and the whole eval dies at the
# first image with an opaque HTTP error -- this file previously had no way to
# authenticate at all. Populated from --api-key, else IMAGEFORGE_API_KEY, else
# the same ~/.imageforge/secrets.env the server itself reads, so an eval on a
# box with auth already enabled just works.
API_KEY: Optional[str] = None
def _load_api_key_from_secrets() -> Optional[str]:
"""Read IMAGEFORGE_API_KEY out of ~/.imageforge/secrets.env.
Deliberately a tiny stdlib parser rather than a python-dotenv dependency:
this harness is run from a bare eval environment (clean-fid/hpsv2/httpx
only) and must not grow install steps just to read one KEY=value line.
"""
path = Path.home() / ".imageforge" / "secrets.env"
try:
for line in path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
if key.strip() == "IMAGEFORGE_API_KEY":
return value.strip().strip('"').strip("'") or None
except OSError:
return None
return None
def _auth_headers() -> dict:
"""Headers for every outbound API call.
X-Client-Name makes this harness show up as a named caller in the API's
own GET /clients registry instead of an anonymous User-Agent, so a long
eval run is attributable while it is happening.
"""
headers = {"X-Client-Name": "eval_harness"}
if API_KEY:
headers["X-API-Key"] = API_KEY
return headers
# Pass/fail gate thresholds (see emit_report for the gate model).
#
# Gate model (redesigned):
# * HPSv2 is the PRIMARY gate — higher is better, always measurable, so the
# gate always rests on it. Delta ≥ +0.20 AND > 2×noise_std is pass.
# * clean-FID is a CORROBORATING signal computed ONLY against a real-image
# reference set (--reference-dir): fid_base = FID(ref, base),
# fid_cand = FID(ref, cand); delta = fid_cand - fid_base must be ≤ -5 (and
# beyond the noise floor) — a LOWER candidate FID is the improvement.
# With no reference set FID is N/A and does not gate (never fabricated).
# * GenEval2 Soft-TIFA_AM: higher is better. Delta ≥ +2.0 pp AND > 2×noise_std.
FID_PASS_DELTA = -5.0 # candidate FID(ref,cand) lower than base FID(ref,base) by ≥5 → corroborates
HPS_PASS_DELTA = 0.20 # candidate HPS higher by ≥0.20 points (100-scale) → pass
GENEVAL_PASS_DELTA = 2.0 # candidate Soft-TIFA_AM higher by ≥2.0 pp → pass
NOISE_SIGMA_MULTIPLIER = 2.0 # delta must also exceed 2×noise_std (per metric)
# Number of images per model run. 200 images gives ±0.3 FID CI vs ±0.2 at N=1000.
# For a LoRA vs base comparison on a held-out prompt set, N=200 is adequate.
DEFAULT_N_IMAGES = 200 # use --n-images to override
# Default resolution — matches the sd-turbo/sdxl-turbo defaults in the registry.
DEFAULT_WIDTH = 512
DEFAULT_HEIGHT = 512
# Below this, an SDXL-architecture model does not merely look worse -- it
# collapses into tiled, saturated abstract mush. Scoring THAT with HPSv2
# produces a real-looking number computed over garbage, and because both the
# base and the candidate degrade the same way, the delta stays plausibly near
# zero and the gate reads as a legitimate "no improvement" verdict. A silently
# meaningless gate is worse than a loud failure, hence the guard below.
SDXL_MIN_USABLE_RESOLUTION = 768
def _looks_like_sdxl(model_key: Optional[str]) -> bool:
"""True for SDXL-architecture models that actually need >=768px.
Turbo variants are deliberately excluded. `sdxl-turbo` is SDXL-architecture
but is a distilled model TRAINED at 512 -- checked against the registry, it
is the only `sdxl-*` entry with `default_size=512`, and it is exactly the
one carrying `turbo=True`; every other sdxl-* is 1024. Flagging it would
reject the harness's own default candidate for a problem it does not have.
This is a string heuristic on purpose: the harness runs from a bare eval
environment that cannot import imageforge to consult MODEL_REGISTRY.
"""
if not model_key:
return False
key = model_key.lower()
if "turbo" in key:
return False
return "xl" in key
def _check_resolution_sanity(
base: Optional[str],
candidate: Optional[str],
width: Optional[int],
height: Optional[int],
) -> tuple[int, int]:
"""Resolve --width/--height and refuse a silently-meaningless SDXL eval.
Returns the (width, height) to use.
The distinction that matters is INTENT. Explicitly passing a small size
is a legitimate thing to want (a fast smoke run, reproducing an old
result), so that only warns. Falling into 512 because the default was
written for sd-turbo, while evaluating SDXL, is not a choice anyone made
-- and it yields a gate verdict computed entirely over degenerate images.
That is refused, with the fix spelled out.
"""
defaulted = width is None and height is None
w = width if width is not None else DEFAULT_WIDTH
h = height if height is not None else DEFAULT_HEIGHT
sdxl_models = [m for m in (base, candidate) if _looks_like_sdxl(m)]
if sdxl_models and min(w, h) < SDXL_MIN_USABLE_RESOLUTION:
message = (
f"{sdxl_models} is SDXL-architecture but the eval resolution is {w}x{h}. "
f"SDXL degenerates into tiled abstract mush below {SDXL_MIN_USABLE_RESOLUTION}px; "
"HPSv2 would score garbage for BOTH models and the delta would look "
"like a legitimate 'no improvement' verdict."
)
if defaulted:
sys.exit(
f"REFUSING TO RUN: {message}\n"
f" This resolution came from the default ({DEFAULT_WIDTH}x{DEFAULT_HEIGHT}), which is "
"sized for sd-turbo, not from anything you asked for.\n"
f" Fix: pass --width 1024 --height 1024 (or any size >= {SDXL_MIN_USABLE_RESOLUTION}).\n"
" To override deliberately, pass the small size explicitly."
)
log.warning("EXPLICIT small resolution for an SDXL model: %s", message)
return w, h
# ---------------------------------------------------------------------------
# Prompt set loader
# ---------------------------------------------------------------------------
PROMPTS_FILE = Path(__file__).parent / "prompts_heldout.jsonl"
def load_prompts(path: Path) -> list[dict]:
"""Load JSONL prompt set. Each line: {"prompt": str, "seed": int, ...}"""
if not path.exists():
raise FileNotFoundError(
f"Prompt file not found: {path}\n"
"Create prompts_heldout.jsonl next to eval_harness.py, or pass --prompts."
)
records = []
with path.open() as fh:
for line in fh:
line = line.strip()
if line and not line.startswith("//"):
records.append(json.loads(line))
log.info("Loaded %d prompts from %s", len(records), path)
return records
# ---------------------------------------------------------------------------
# Image generation driver
# ---------------------------------------------------------------------------
def generate_images(
prompts: list[dict],
model: Optional[str],
out_dir: Path,
*,
seed_offset: int = 0,
steps: Optional[int] = None,
guidance: Optional[float] = None,
width: int = DEFAULT_WIDTH,
height: int = DEFAULT_HEIGHT,
n_images: int = DEFAULT_N_IMAGES,
) -> list[tuple[Path, dict]]:
"""
POST each prompt to /generate, save returned PNG to out_dir.
Respects the engine's single-inference-lock: sends one request at a time
(no concurrency) with a 300s per-image timeout.
Seeds are pinned per-prompt (prompt["seed"] + seed_offset) for reproducibility.
The engine uses torch.Generator(device="cpu").manual_seed(seed) which is
deterministic across MPS restarts (pipeline.py:573).
Returns a list of (image_path, prompt_record) pairs -- NOT just paths.
Bug fixed here: this used to return a bare list[Path], and any single
failed request (network blip, one bad base64) was `continue`d past,
shrinking the list by one with no marker of WHICH prompt was skipped.
Downstream, score_hps()/build_geneval_image_map() re-derived prompt
alignment by re-tiling the original prompt list to len(images) and
zip()-ping positionally -- so every image after a single dropped one
silently shifted onto the WRONG prompt for the rest of the batch, with
no exception and no warning, just a plausible-looking but wrong score.
Pairing the prompt with its image at the moment it's actually saved
makes misalignment structurally impossible instead of re-derived.
"""
try:
import httpx
except ImportError:
sys.exit("httpx not installed. Run: pip install httpx")
out_dir.mkdir(parents=True, exist_ok=True)
saved: list[tuple[Path, dict]] = []
# Tile prompts up to n_images if fewer prompts than requested
tiled: list[dict] = []
while len(tiled) < n_images:
tiled.extend(prompts)
tiled = tiled[:n_images]
if len(prompts) < n_images:
# Transparency, not a behavior change: each unique prompt repeats
# exactly (n_images // len(prompts)) times, and every repeat reuses
# that record's OWN "seed" field verbatim (idx only affects the
# fallback default when a record has no explicit seed) -- so with
# the default prompts_heldout.jsonl (30 records, every one already
# carries an explicit seed) and DEFAULT_N_IMAGES=200, most of "N=200
# samples" are pixel-identical duplicates of ~30 real generations,
# not independent samples. This understates true variance for both
# FID (near-singular covariance risk) and HPS. Not silently changing
# seed derivation here (that would break reproducibility of any
# past eval run compared against this code) -- just surfacing it.
log.warning(
"n_images=%d > %d available prompts -- each prompt repeats ~%.1fx "
"with its own seed reused verbatim on every repeat (pixel-identical "
"duplicates, not independent samples). Pass more prompts or reduce "
"--n-images for a truly independent sample.",
n_images, len(prompts), n_images / len(prompts),
)
label = model or "default"
log.info("Generating %d images with model=%s → %s", len(tiled), label, out_dir)
with httpx.Client(base_url=API_URL, timeout=300.0, headers=_auth_headers()) as client:
# Health check first — fail fast rather than timeout N times
try:
health = client.get("/health").json()
log.info("Engine health: status=%s device=%s", health.get("status"), health.get("device"))
except Exception as e:
sys.exit(f"Cannot reach ImageForge at {API_URL}. Start with: ./run_api.sh\nError: {e}")
for idx, rec in enumerate(tiled):
seed = (rec.get("seed", idx * 1000) + seed_offset) & 0xFFFFFFFF
payload: dict = {
"prompt": rec["prompt"],
"seed": seed,
"width": width,
"height": height,
"return_mode": "base64",
"use_cache": False, # always generate fresh for eval
}
if model:
payload["model"] = model
if steps is not None:
payload["steps"] = steps
if guidance is not None:
payload["guidance"] = guidance
out_file = out_dir / f"{idx:04d}_seed{seed}.png"
if out_file.exists():
log.debug("[%d/%d] cached %s", idx + 1, len(tiled), out_file.name)
saved.append((out_file, rec))
continue
t0 = time.perf_counter()
try:
resp = client.post("/generate", json=payload)
resp.raise_for_status()
except httpx.HTTPStatusError as e:
log.error("[%d/%d] HTTP %s: %s", idx + 1, len(tiled), e.response.status_code, e.response.text[:200])
continue
except Exception as e:
log.error("[%d/%d] request failed: %s", idx + 1, len(tiled), e)
continue
data = resp.json()
b64 = data.get("image_base64")
if not b64:
log.warning("[%d/%d] no image_base64 in response: %s", idx + 1, len(tiled), list(data.keys()))
continue
img_bytes = base64.b64decode(b64)
out_file.write_bytes(img_bytes)
elapsed = time.perf_counter() - t0
log.info("[%d/%d] seed=%d %.1fs → %s", idx + 1, len(tiled), seed, elapsed, out_file.name)
saved.append((out_file, rec))
if len(saved) < len(tiled):
log.warning(
"Only %d/%d images generated successfully -- the real sample size "
"for scoring is %d, not the requested %d.",
len(saved), len(tiled), len(saved), len(tiled),
)
log.info("Generated %d/%d images", len(saved), len(tiled))
return saved
# ---------------------------------------------------------------------------
# clean-FID scoring (on-Mac, CPU or MPS via torch device override)
# ---------------------------------------------------------------------------
def score_fid(dir_base: Path, dir_candidate: Path, *, device_str: str = "cpu") -> float:
"""
Compute clean-FID between two image directories.
Uses mode='clean' (PIL-bicubic resizing) to avoid the Parmar 2022 resize bug
where OpenCV/PyTorch bicubic produced FID ≥6 offset vs correct PIL-bicubic.
device_str: 'cpu' for Mac MPS box (Inception runs fine on CPU, ~2min for N=200).
'cuda' for the CUDA training box.
"""
try:
from cleanfid import fid
except ImportError:
sys.exit("clean-fid not installed. Run: pip install clean-fid")
import torch
device = torch.device(device_str)
log.info("Computing FID: %s vs %s (device=%s) …", dir_base.name, dir_candidate.name, device_str)
score = fid.compute_fid(
str(dir_base),
str(dir_candidate),
mode="clean", # correct PIL-bicubic resize — never legacy_pytorch/legacy_tensorflow
model_name="inception_v3",
num_workers=0, # 0 = no multiprocessing (avoids fork issues on macOS)
batch_size=32,
device=device,
verbose=True,
)
return float(score)
# ---------------------------------------------------------------------------
# HPSv2 scoring (on-Mac, CPU or MPS)
# ---------------------------------------------------------------------------
def score_hps_per_image(
image_prompt_pairs: list[tuple[Path, dict]],
*,
hps_version: str = "v2.1",
) -> list[tuple[Path, dict, float]]:
"""Return per-image HPSv2 scores as ``(image_path, prompt_record, score)``.
This is the raw, per-image basis both :func:`score_hps` (which averages it)
and the paired bootstrap CI (which needs the individual samples, not just
the mean) consume. Keeping alignment with the source ``(path, prompt)``
pair here means the bootstrap pairs candidate-vs-base by IMAGE INDEX with
no positional re-derivation. Images that fail to score are omitted from
the returned list (logged), so a caller can detect a shrunk sample.
"""
try:
import hpsv2
except ImportError:
sys.exit("hpsv2 not installed. Run: pip install hpsv2")
out: list[tuple[Path, dict, float]] = []
log.info("Scoring %d images with HPSv2.%s …", len(image_prompt_pairs), hps_version)
for img_path, rec in image_prompt_pairs:
try:
result = hpsv2.score(str(img_path), rec["prompt"], hps_version=hps_version)
# hpsv2.score returns a list when given a list of images; a scalar for a single path
val = result[0] if isinstance(result, (list, tuple)) else float(result)
out.append((img_path, rec, float(val)))
except Exception as e:
log.warning("HPSv2 error on %s: %s", img_path.name, e)
return out
def score_hps(
image_prompt_pairs: list[tuple[Path, dict]],
*,
hps_version: str = "v2.1",
dump_scores_path: "Optional[Path]" = None,
) -> float:
"""
Compute mean HPSv2 score for a list of (image_path, prompt_record) pairs.
hpsv2.score(img, prompt) accepts: PIL.Image, file path str, or list.
Returns a logit score; typical range for SDXL-class models: 26–30 on 100-scale.
We use v2.1 (released Sep 2024, trained on higher-quality HPD v2.1 dataset).
Runs on CPU perfectly. MPS is NOT supported -- hpsv2's own img_score.py
hardcodes device selection to "cuda" or "cpu" and never checks
torch.backends.mps (verified directly against the installed hpsv2
package's source; this docstring previously claimed otherwise).
The reward model is a CLIP-ViT-H variant (~900MB download on first run).
Takes (path, prompt) pairs directly from generate_images() -- previously
took separate images/prompts lists and RE-DERIVED alignment by re-tiling
prompts to len(images) and zip()-ping positionally. Any single dropped
image during generation shifted every subsequent image onto the wrong
prompt for the rest of the batch, silently. Pairing at the source makes
that class of bug structurally impossible here.
Batch 1: ``dump_scores_path`` -- when given, the per-image scores are
persisted as JSON (a list of ``{"image": name, "prompt": text, "hps":
score}`` records) so a paired bootstrap CI can be recomputed offline from
the raw samples, not just the mean. Best-effort: a write failure is logged
and never fails scoring.
"""
scored = score_hps_per_image(image_prompt_pairs, hps_version=hps_version)
if dump_scores_path is not None:
try:
dump_scores_path.parent.mkdir(parents=True, exist_ok=True)
dump_scores_path.write_text(
json.dumps(
[
{"image": p.name, "prompt": rec.get("prompt"), "hps": s}
for p, rec, s in scored
],
indent=2,
),
encoding="utf-8",
)
log.info("Persisted %d per-image HPS scores → %s", len(scored), dump_scores_path)
except OSError as e:
log.warning("Could not persist per-image HPS scores to %s: %s", dump_scores_path, e)
if not scored:
return float("nan")
scores = [s for _p, _rec, s in scored]
mean_score = sum(scores) / len(scores)
log.info("HPSv2 mean=%.4f (N=%d)", mean_score, len(scores))
return mean_score
# ---------------------------------------------------------------------------
# Paired bootstrap CI on the base-vs-candidate HPS delta (Batch 1)
# ---------------------------------------------------------------------------
def paired_bootstrap_ci(
base_scores: "list[float]",
cand_scores: "list[float]",
*,
pass_delta: float = HPS_PASS_DELTA,
n_boot: int = 10_000,
ci_level: float = 0.95,
seed: int = 1234,
) -> dict:
"""Paired bootstrap confidence interval on the mean ``cand - base`` delta.
The two inputs are aligned per-image: ``delta_i = cand_scores[i] -
base_scores[i]``. We resample the *paired* deltas (not the two batches
independently) ``n_boot`` times with replacement and take the empirical
percentile interval of the resampled mean delta. Pairing preserves the
per-prompt correlation between base and candidate (same prompt+seed), which
an unpaired two-sample bootstrap would throw away, inflating the CI.
Gate (matches the roadmap): the candidate PASSES iff the CI lies entirely
ABOVE zero (``ci_low > 0`` -- a real, direction-correct improvement, not
merely "excludes zero") AND the observed mean delta is at least
``pass_delta`` in magnitude. ``ci_excludes_zero`` is reported separately
for transparency (a CI entirely below zero is a real regression, not a
pass). Deterministic for a fixed ``seed`` -- uses ``random.Random`` so the
result never depends on numpy's RNG version.
Returns a dict with: n, delta_mean, ci_low, ci_high, ci_level, n_boot,
seed, pass_delta, ci_excludes_zero, passes, error (None on success).
A length mismatch or empty input returns an all-NaN result with a set
``error`` string rather than raising, so the report degrades gracefully.
"""
import math
import random as _random
n = len(base_scores)
base_ok = all(x == x for x in base_scores) # not NaN
cand_ok = all(x == x for x in cand_scores)
if n == 0 or len(cand_scores) != n or not base_ok or not cand_ok:
return {
"n": n,
"delta_mean": float("nan"),
"ci_low": float("nan"),
"ci_high": float("nan"),
"ci_level": ci_level,
"n_boot": n_boot,
"seed": seed,
"pass_delta": pass_delta,
"ci_excludes_zero": False,
"passes": False,
"error": (
"length mismatch"
if (n and len(cand_scores) != n)
else "empty input" if n == 0
else "NaN score(s) present"
),
}
deltas = [c - b for b, c in zip(base_scores, cand_scores)]
delta_mean = sum(deltas) / n
rng = _random.Random(seed)
boot_means: list[float] = []
for _ in range(n_boot):
acc = 0.0
for _ in range(n):
acc += deltas[rng.randrange(n)]
boot_means.append(acc / n)
boot_means.sort()
alpha = (1.0 - ci_level) / 2.0
lo_idx = int(math.floor(alpha * n_boot))
hi_idx = int(math.ceil((1.0 - alpha) * n_boot)) - 1
lo_idx = max(0, min(lo_idx, n_boot - 1))
hi_idx = max(0, min(hi_idx, n_boot - 1))
ci_low = boot_means[lo_idx]
ci_high = boot_means[hi_idx]
ci_excludes_zero = ci_low > 0.0 or ci_high < 0.0
passes = (ci_low > 0.0) and (delta_mean >= pass_delta)
return {
"n": n,
"delta_mean": delta_mean,
"ci_low": ci_low,
"ci_high": ci_high,
"ci_level": ci_level,
"n_boot": n_boot,
"seed": seed,
"pass_delta": pass_delta,
"ci_excludes_zero": ci_excludes_zero,
"passes": passes,
"error": None,
}
# ---------------------------------------------------------------------------
# GenEval2 Soft-TIFA scoring (run on CUDA box via SSH or local if 4090 present)
# ---------------------------------------------------------------------------
def build_geneval_image_map(image_prompt_pairs: list[tuple[Path, dict]], run_dir: Path) -> Path:
"""
Build the image_filepath_data.json that GenEval2's evaluation.py expects.
Format: {"<prompt_text>": "<absolute_path_to_image>"}
Takes (path, prompt) pairs directly from generate_images() -- see
score_hps()'s docstring for why re-deriving alignment via re-tiling was
a real bug, fixed the same way here.
GenEval2's own expected format keys by prompt TEXT, an external
constraint of the tool this project doesn't control -- so when
n_images exceeds the number of unique prompts (the default config
does: DEFAULT_N_IMAGES=200 vs 30 heldout prompts), a later repeat of an
already-seen prompt still overwrites the map entry for an earlier one.
That's not fixable without changing GenEval2's own input contract, but
it was previously silent; now it's logged so a caller can tell GenEval2
scored fewer effective images than HPS/FID did in the same report.
"""
mapping: dict[str, str] = {}
for img_path, rec in image_prompt_pairs:
prompt_text = rec["prompt"]
# GenEval2 uses prompt as key; use last image if duplicated prompts
mapping[prompt_text] = str(img_path.resolve())
dropped = len(image_prompt_pairs) - len(mapping)
if dropped > 0:
log.warning(
"%d of %d images share a prompt with another image already in the "
"map -- GenEval2 will only score %d unique prompts, not %d images "
"(an inherent limit of GenEval2's own prompt-keyed input format, "
"not a bug in this mapping step).",
dropped, len(image_prompt_pairs), len(mapping), len(image_prompt_pairs),
)
out_path = run_dir / "geneval_image_map.json"
out_path.write_text(json.dumps(mapping, indent=2), encoding="utf-8")
log.info("Wrote GenEval2 image map → %s (%d entries)", out_path, len(mapping))
return out_path
def score_geneval2(
image_map_path: Path,
geneval2_repo: str,
*,
method: str = "soft_tifa_am",
geneval2_data: Optional[str] = None,
output_file: Optional[Path] = None,
timeout: float = 1800.0,
) -> float:
"""
Run GenEval2 evaluation.py as a subprocess.
geneval2_repo: path to the cloned facebookresearch/GenEval2 directory.
method: 'soft_tifa_am' (atom-level arithmetic mean, recommended for LoRA delta).
'soft_tifa_gm' is more conservative (geometric mean, sensitive to zero atoms).
timeout: seconds before the subprocess is killed (default 30 min) -- this
previously had NO timeout at all, so a VLM-scoring hang (model load
stall, GPU contention) blocked the whole harness indefinitely with no
way to recover short of manually killing the process. The caller
already wraps this call in try/except, so a TimeoutExpired here
degrades gracefully to a skipped GenEval2 row, same as any other
scoring failure -- it just no longer hangs forever getting there.
Returns: aggregate score (0–100).
NOTE: GenEval2 requires Qwen3-VL-8B-Instruct (~19GB VRAM at FP16, ~5GB at INT4).
Run on the RTX 4090 (CUDA box). Pass --skip-geneval on the Mac if not available.
"""
import subprocess
repo = Path(geneval2_repo).resolve()
eval_script = repo / "evaluation.py"
if not eval_script.exists():
raise FileNotFoundError(f"GenEval2 evaluation.py not found at {eval_script}")
data_path = geneval2_data or str(repo / "geneval2_data.jsonl")
out_path = output_file or image_map_path.parent / "geneval2_scores.json"
cmd = [
sys.executable, str(eval_script),
"--benchmark_data", data_path,
"--image_filepath_data", str(image_map_path),
"--method", method,
"--output_file", str(out_path),
]
log.info("Running GenEval2: %s", " ".join(cmd))
try:
result = subprocess.run(cmd, capture_output=True, text=True, cwd=str(repo), timeout=timeout)
except subprocess.TimeoutExpired as exc:
raise RuntimeError(f"GenEval2 evaluation.py timed out after {timeout:.0f}s") from exc
if result.returncode != 0:
log.error("GenEval2 stderr:\n%s", result.stderr[-2000:])
raise RuntimeError(f"GenEval2 evaluation.py exited {result.returncode}")
log.info("GenEval2 stdout:\n%s", result.stdout[-2000:])
if not out_path.exists():
raise FileNotFoundError(f"GenEval2 output not written: {out_path}")
scores_data = json.loads(out_path.read_text(encoding="utf-8"))
# Expected structure: list of per-atom scores or a dict with "score" key.
# Aggregate: arithmetic mean of all atom scores (0–1), then ×100.
if isinstance(scores_data, list):
flat = [v for entry in scores_data for v in (entry if isinstance(entry, list) else [entry]) if isinstance(v, (int, float))]
elif isinstance(scores_data, dict) and "score" in scores_data:
return float(scores_data["score"])
else:
flat = list(scores_data.values()) if isinstance(scores_data, dict) else []
if not flat:
return float("nan")
return 100.0 * sum(flat) / len(flat)
# ---------------------------------------------------------------------------
# Noise floor estimation (base vs base, different seeds)
# ---------------------------------------------------------------------------
def estimate_noise_floor(
prompts: list[dict],
model: Optional[str],
run_dir: Path,
*,
width: int,
height: int,
n_images: int,
hps_version: str,
seed_offset_a: int = 0,
seed_offset_b: int = 100_000,
) -> dict[str, float]:
"""
Generate two batches from the same model with offset seeds.
Returns FID and HPS std-dev between the two runs as noise floor estimates.
"""
log.info("Estimating noise floor: %s run A vs run B …", model or "default")
dir_a = run_dir / "noise_a"
dir_b = run_dir / "noise_b"
imgs_a = generate_images(prompts, model, dir_a, seed_offset=seed_offset_a, width=width, height=height, n_images=n_images)
imgs_b = generate_images(prompts, model, dir_b, seed_offset=seed_offset_b, width=width, height=height, n_images=n_images)
fid_noise = score_fid(dir_a, dir_b)
hps_a = score_hps(imgs_a, hps_version=hps_version)
hps_b = score_hps(imgs_b, hps_version=hps_version)
# std of two-point estimate = |a - b| / sqrt(2) (conservative)
import math
hps_noise_std = abs(hps_a - hps_b) / math.sqrt(2)
return {
"fid_a": fid_noise, # FID between same-model different-seed runs
"hps_a": hps_a,
"hps_b": hps_b,
"hps_noise_std": hps_noise_std,
"fid_noise_floor": fid_noise, # treat same-model FID as noise floor for FID
}
# ---------------------------------------------------------------------------
# Batch 23: Anatomy plausibility (hands/limbs) via mediapipe hand landmarks
# ---------------------------------------------------------------------------
#
# IMPORTANT SCOPE / LIMITATION (stated plainly, not overclaimed):
# mediapipe's hand landmarker fits a FIXED 21-point / 5-finger template onto
# whatever it detects. It does NOT count fingers -- it structurally CANNOT
# flag "this hand has six fingers" or "two fingers are fused", because it
# always returns exactly 21 points regardless of the true digit count. No
# permissively-licensed fully-automated polydactyly/finger-count detector
# exists today (OpenPose weights are CMU non-commercial; MMPose is Apache-2.0
# but a far heavier torch/mmcv chain for no clear win here). So this is a
# HEURISTIC SANITY CHECK, not a correctness guarantee, built from the two
# real, cheap, deterministic signals mediapipe DOES give:
# (a) detection confidence / detect-vs-no-detect -- broken or fused AI
# hands frequently fail to trigger detection at all, or trigger only
# at low confidence. A real plausibility proxy.
# (b) geometric plausibility of the 21 points it DID return -- finger
# segment-length ratios within human proportion bounds, and no
# impossible interior joint angles.
# Thresholds below are a FIRST CALIBRATION, not authoritative numbers, and
# are labelled as such in the report (same spirit as "UNVERIFIED NOISE
# FLOOR").
#
# mediapipe is CPU-only and an OPTIONAL dependency: absent it, --skip-anatomy-
# check (or the automatic availability guard) lets the rest of the harness run,
# mirroring the clean-fid / hpsv2 optional-dependency pattern.
# MediaPipe 21-landmark hand topology (fixed indices):
# 0 wrist; thumb 1-4 (CMC,MCP,IP,TIP); index 5-8; middle 9-12; ring 13-16;
# pinky 17-20 (each: MCP, PIP, DIP, TIP).
_FINGERS: "dict[str, tuple[int, int, int, int]]" = {
"thumb": (1, 2, 3, 4),
"index": (5, 6, 7, 8),
"middle": (9, 10, 11, 12),
"ring": (13, 14, 15, 16),
"pinky": (17, 18, 19, 20),
}
# Non-thumb fingers have a clean proximal>middle>distal phalanx ordering; the
# thumb's metacarpal/phalanx geometry differs, so proportion checks skip it.
_NON_THUMB = ("index", "middle", "ring", "pinky")
# First-calibration heuristic bounds (loose on purpose -- tuned to NOT flag
# real, correctly-articulated human hands, at the cost of missing subtle
# defects; see the module note above on why this is a sanity check only).
_RATIO_MID_OVER_PROX = (0.30, 1.05) # middle-phalanx / proximal-phalanx length
_RATIO_DIST_OVER_MID = (0.30, 1.15) # distal-phalanx / middle-phalanx length
_MIN_INTERIOR_ANGLE_DEG = 18.0 # sharper than this at a joint = implausible kink
# Report gate thresholds (FIRST CALIBRATION -- see note above).
ANATOMY_DETECT_RATE_MIN = 0.60 # >=60% of hand prompts should trigger a detection
ANATOMY_PLAUSIBILITY_MIN = 0.70 # mean geometric-plausibility of detected hands
FIDELITY_STRUCT_DELTA_MAX = 0.35 # per-image edit structural delta above this = degradation
def _euclid(a: "tuple[float, float, float]", b: "tuple[float, float, float]") -> float:
return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2) ** 0.5
def _interior_angle_deg(
a: "tuple[float, float, float]",
b: "tuple[float, float, float]",
c: "tuple[float, float, float]",
) -> float:
"""Angle at vertex ``b`` formed by segments b->a and b->c, in degrees.
Returns 180.0 (straight, maximally plausible) for a degenerate zero-length
segment rather than raising."""
import math
v1 = (a[0] - b[0], a[1] - b[1], a[2] - b[2])
v2 = (c[0] - b[0], c[1] - b[1], c[2] - b[2])
n1 = (v1[0] ** 2 + v1[1] ** 2 + v1[2] ** 2) ** 0.5
n2 = (v2[0] ** 2 + v2[1] ** 2 + v2[2] ** 2) ** 0.5
if n1 == 0.0 or n2 == 0.0:
return 180.0
dot = v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]
cos = max(-1.0, min(1.0, dot / (n1 * n2)))
return math.degrees(math.acos(cos))
def _hand_scale(landmarks: "list[tuple[float, float, float]]") -> float:
"""A rotation/translation-invariant size reference for the hand: the
wrist(0)->middle-MCP(9) distance. Used to normalise segment lengths so the
signature is comparable across image scales (input vs edited output)."""
s = _euclid(landmarks[0], landmarks[9])
return s if s > 1e-9 else 1e-9
def geometric_plausibility(landmarks: "list[tuple[float, float, float]]") -> float:
"""Heuristic geometric-plausibility score in [0, 1] for one detected hand.
1.0 = every proportion + joint-angle check passed (looks like a well-
articulated human hand); 0.0 = every check failed (impossible geometry, or
a degenerate all-identical / NaN landmark set). This is the (b) signal from
the module note -- it operates purely on the 21 returned points and knows
NOTHING about how many real fingers were in the image.
Returns 0.0 for anything other than a well-formed 21-point list (defensive:
a degenerate/blank detection must read as implausible, never crash)."""
import math
if not landmarks or len(landmarks) != 21:
return 0.0
for p in landmarks:
if len(p) != 3 or any(math.isnan(c) or math.isinf(c) for c in p):
return 0.0
scale = _hand_scale(landmarks)
checks: list[bool] = []
for name in _NON_THUMB:
mcp, pip, dip, tip = _FINGERS[name]
prox = _euclid(landmarks[mcp], landmarks[pip]) / scale
mid = _euclid(landmarks[pip], landmarks[dip]) / scale
dist = _euclid(landmarks[dip], landmarks[tip]) / scale
# A collapsed finger (any near-zero phalanx -- e.g. an all-identical
# degenerate landmark set) is anatomically impossible: fail ALL four of
# this finger's checks rather than letting the zero-length angle default
# to "straight" and score it half-plausible.
if prox <= 1e-6 or mid <= 1e-6 or dist <= 1e-6:
checks.extend([False, False, False, False])
continue
# Proportion checks: successive phalanges shrink, ratios within bounds.
r_mp = mid / prox
checks.append(_RATIO_MID_OVER_PROX[0] <= r_mp <= _RATIO_MID_OVER_PROX[1])
r_dm = dist / mid
checks.append(_RATIO_DIST_OVER_MID[0] <= r_dm <= _RATIO_DIST_OVER_MID[1])
# Interior joint angles: no impossibly-sharp kink at PIP or DIP.
ang_pip = _interior_angle_deg(landmarks[mcp], landmarks[pip], landmarks[dip])
ang_dip = _interior_angle_deg(landmarks[pip], landmarks[dip], landmarks[tip])
checks.append(ang_pip >= _MIN_INTERIOR_ANGLE_DEG)
checks.append(ang_dip >= _MIN_INTERIOR_ANGLE_DEG)
if not checks:
return 0.0
return sum(1 for c in checks if c) / len(checks)
def structural_signature(landmarks: "list[tuple[float, float, float]]") -> "list[float]":
"""Scale-normalised structural feature vector for before/after comparison.
Concatenates, for all 5 fingers: the 3 phalanx segment lengths (each
divided by hand scale) and the 2 interior joint angles (normalised to
[0, 1] by /180). Length = 5*(3+2) = 25. This is what the img2img/inpaint
FIDELITY test diffs between the ORIGINAL photo's hand and the EDITED
output's hand: a large delta means the edit moved real anatomy.
Returns an empty list for a malformed landmark set (caller treats an empty
signature as "no comparable structure")."""
import math
if not landmarks or len(landmarks) != 21:
return []
for p in landmarks:
if len(p) != 3 or any(math.isnan(c) or math.isinf(c) for c in p):
return []
scale = _hand_scale(landmarks)
sig: list[float] = []
for name in ("thumb",) + _NON_THUMB:
a, b, c, d = _FINGERS[name]
sig.append(_euclid(landmarks[a], landmarks[b]) / scale)
sig.append(_euclid(landmarks[b], landmarks[c]) / scale)
sig.append(_euclid(landmarks[c], landmarks[d]) / scale)
sig.append(_interior_angle_deg(landmarks[a], landmarks[b], landmarks[c]) / 180.0)
sig.append(_interior_angle_deg(landmarks[b], landmarks[c], landmarks[d]) / 180.0)
return sig
def structural_delta(
sig_before: "list[float]",
sig_after: "list[float]",
) -> float:
"""Mean absolute difference between two structural signatures.
0.0 = identical structure (edit preserved the hand perfectly); larger =
more structural drift. NaN when the signatures are empty or mismatched
(no comparable hand on one side) so the caller can skip, not fabricate a
zero. Monotonic in perturbation magnitude: a bigger geometric change
yields a strictly larger delta -- the property the fidelity test asserts."""
if not sig_before or not sig_after or len(sig_before) != len(sig_after):
return float("nan")
return sum(abs(a - b) for a, b in zip(sig_before, sig_after)) / len(sig_before)
# Canonical Google-hosted hand-landmarker asset (Apache-2.0). The mediapipe
# Tasks API needs this .task file (the legacy solutions.hands API that bundled
# weights in the wheel was removed in mediapipe 0.10.x). Resolution order:
# 1. $IMAGEFORGE_HAND_LANDMARKER_TASK (an explicit local path)
# 2. a cached copy under ~/.cache/imageforge/
# 3. one-time best-effort download from the URL below into that cache
# -- the same "download real weights on first use" pattern hpsv2/clean-fid
# already use. When it can't be resolved, _mediapipe_hands raises and the
# anatomy section auto-skips (never fabricated, never fatal to the main eval).
_HAND_LANDMARKER_URL = (
"https://storage.googleapis.com/mediapipe-models/hand_landmarker/"
"hand_landmarker/float16/1/hand_landmarker.task"
)
def _resolve_hand_landmarker_task() -> "Path":
env = os.environ.get("IMAGEFORGE_HAND_LANDMARKER_TASK")
if env:
p = Path(env)
if not p.is_file():
raise ImportError(
f"IMAGEFORGE_HAND_LANDMARKER_TASK={env} is not a file. Point it at a "
"downloaded hand_landmarker.task, or unset it to use the cache."
)
return p
cache = Path.home() / ".cache" / "imageforge" / "hand_landmarker.task"
if cache.is_file():
return cache
cache.parent.mkdir(parents=True, exist_ok=True)
log.info("Downloading hand_landmarker.task (one-time, ~7.5MB) → %s", cache)
try:
import urllib.request
tmp = cache.with_suffix(".task.part")
urllib.request.urlretrieve(_HAND_LANDMARKER_URL, tmp)
tmp.replace(cache)
except Exception as exc: # noqa: BLE001
raise ImportError(
"Could not obtain hand_landmarker.task automatically "
f"({exc}). Download it from {_HAND_LANDMARKER_URL} and set "
"IMAGEFORGE_HAND_LANDMARKER_TASK to its path, or pass "
"--skip-anatomy-check."
) from exc
return cache
def _mediapipe_hands():
"""Construct a mediapipe Tasks-API ``HandLandmarker`` detector.
Returns 21 fixed 3D landmarks + handedness (with a confidence score) per
detected hand. Raises ImportError with an install hint when mediapipe is
absent OR the model asset cannot be resolved, so the caller degrades to a
skipped anatomy section exactly like a missing clean-fid/hpsv2. A low
detection floor (0.3) is deliberate -- we WANT to observe low-confidence