File size: 12,251 Bytes
f9ed2b4 | 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 | #!/usr/bin/env python3
'Build zero-shot and jointly supervised cross-dataset training and evaluation manifests.'
from __future__ import annotations
import argparse
import csv
import hashlib
import json
import sys
from collections import defaultdict
from pathlib import Path
from typing import Any
PROJECT_ROOT = Path(__file__).resolve().parents[2]
SPLIT_DIR = PROJECT_ROOT / "artifacts" / "metadata" / "fixed_split"
DEFAULT_OUTPUT_DIR = PROJECT_ROOT / "artifacts" / "metadata" / "transfer"
TRAINING_SPLIT = PROJECT_ROOT / "artifacts" / "metadata" / "training" / "splits" / "training_split_n900_realratio_0p1_seed42.json"
N_GRID = [900, 90, 18]
ALLOWED_EXTS = {".jpg", ".jpeg", ".png", ".webp"}
csv.field_size_limit(min(sys.maxsize, 2_147_483_647))
def stable_rank(seed: int, group_key: str, sample_id: str) -> int:
key = f"{seed}:{group_key}:{sample_id}".encode("utf-8")
return int(hashlib.sha256(key).hexdigest(), 16)
def read_csv(path: Path) -> list[dict[str, str]]:
with path.open("r", newline="", encoding="utf-8") as f:
return list(csv.DictReader(f))
def write_json(path: Path, data: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
def ratio_tag(value: float) -> str:
return str(value).replace(".", "p")
def ranked_rows(rows: list[dict[str, str]], seed: int, group: str) -> list[dict[str, str]]:
def key(row: dict[str, str]) -> tuple[int, int, str]:
split_rank = row.get("split_rank")
if split_rank not in (None, ""):
return (0, int(split_rank), row["sample_id"])
return (1, stable_rank(seed, group, row["sample_id"]), row["sample_id"])
return sorted(rows, key=key)
def group_ai(rows: list[dict[str, str]]) -> dict[str, list[dict[str, str]]]:
grouped: dict[str, list[dict[str, str]]] = defaultdict(list)
for row in rows:
grouped[row["source_model_id"]].append(row)
return grouped
def manifest_row(path: str, label: int, source: str, source_type: str) -> dict[str, Any]:
return {"path": path, "label": label, "source": source, "source_type": source_type}
def to_manifest_rows(rows: list[dict[str, str]], label: int, source: str, source_type: str) -> list[dict[str, Any]]:
return [manifest_row(row["image_path"], label, source, source_type) for row in rows]
def image_files(path: Path) -> list[str]:
if not path.is_dir():
return []
return [str(p) for p in sorted(path.iterdir()) if p.is_file() and p.suffix.lower() in ALLOWED_EXTS]
def collect_genimage(root: Path) -> dict[str, dict[str, list[str]]]:
data: dict[str, dict[str, list[str]]] = {}
for gen_dir in sorted([p for p in root.iterdir() if p.is_dir()]):
if gen_dir.name.startswith("_"):
continue
fake = image_files(gen_dir / "val" / "ai")
real = image_files(gen_dir / "val" / "nature")
if fake and real:
data[gen_dir.name] = {"fake": fake, "real": real}
return data
def collect_forensynths(root: Path) -> dict[str, dict[str, list[str]]]:
data: dict[str, dict[str, list[str]]] = {}
for gen_dir in sorted([p for p in root.iterdir() if p.is_dir()]):
fake: list[str] = []
real: list[str] = []
if (gen_dir / "0_real").is_dir() and (gen_dir / "1_fake").is_dir():
real.extend(image_files(gen_dir / "0_real"))
fake.extend(image_files(gen_dir / "1_fake"))
else:
for class_dir in sorted([p for p in gen_dir.iterdir() if p.is_dir()]):
real.extend(image_files(class_dir / "0_real"))
fake.extend(image_files(class_dir / "1_fake"))
if fake and real:
data[gen_dir.name] = {"fake": fake, "real": real}
return data
def build_external_manifests(
name: str,
data: dict[str, dict[str, list[str]]],
seed: int,
output_dir: Path,
real_ratio: float = 0.1,
exclude_insufficient_k900: bool = False,
) -> dict[int, Path]:
paths: dict[int, Path] = {}
for k in [0]:
sources = sorted(data)
if exclude_insufficient_k900 and k == 900:
sources = [source for source in sources if len(data[source]["fake"]) >= 1000 and len(data[source]["real"]) >= 900]
train_rows: list[dict[str, Any]] = []
test_rows: list[dict[str, Any]] = []
source_summary: dict[str, dict[str, int]] = {}
for source in sources:
fake = sorted(data[source]["fake"], key=lambda p: stable_rank(seed, f"{name}:fake:{source}", p))
real = sorted(data[source]["real"], key=lambda p: stable_rank(seed, f"{name}:real:{source}", p))
fake_train_count = min(k, len(fake)) if k > 0 else 0
real_train_count = min(int(real_ratio * fake_train_count), len(real)) if k > 0 else 0
if k > 0:
train_rows.extend(manifest_row(p, 1, source, name) for p in fake[:fake_train_count])
train_rows.extend(manifest_row(p, 0, f"real:{source}", "real") for p in real[:real_train_count])
test_rows.extend(manifest_row(p, 1, source, name) for p in fake[fake_train_count:])
test_rows.extend(manifest_row(p, 0, f"real:{source}", "real") for p in real[real_train_count:])
source_summary[source] = {
"fake_total": len(fake),
"real_total": len(real),
"fake_train": fake_train_count,
"real_train": real_train_count,
"fake_test": max(0, len(fake) - fake_train_count),
"real_test": max(0, len(real) - real_train_count),
}
path = output_dir / "manifests" / f"{name}_k{k}_realratio_{ratio_tag(real_ratio)}_seed{seed}.json"
write_json(
path,
{
"name": name,
"k_per_source": k,
"real_ratio": real_ratio,
"sources": sources,
"source_summary": source_summary,
"train": train_rows,
"test": test_rows,
},
)
paths[k] = path
return paths
def load_wildgen_balanced_rows(training_split: Path, k: int, real_ratio: float) -> list[dict[str, Any]]:
"""Take K images per WildGen source (+ real_ratio*K*num_sources pooled real) from the
Phase-2 binary training split. Paths are kept in the split's deterministic order, so the
first K per source is a nested subset across K values."""
with training_split.open("r", encoding="utf-8") as f:
split = json.load(f)
train = split["train"]
ai_ids = sorted([mid for mid in train if mid != "0"], key=int)
rows: list[dict[str, Any]] = []
for mid in ai_ids:
for path in train[mid][:k]:
rows.append(manifest_row(path, 1, f"wildgen:{mid}", "wildgen"))
real_needed = int(real_ratio * k * len(ai_ids))
for path in train["0"][:real_needed]:
rows.append(manifest_row(path, 0, "real:wildgen", "real"))
return rows
def build_joint_external_manifests(
name: str,
data: dict[str, dict[str, list[str]]],
training_split: Path,
seed: int,
output_dir: Path,
real_ratio: float = 0.1,
exclude_insufficient_k900: bool = False,
target_real_ratio: float | None = None,
) -> dict[int, Path]:
"""Balanced joint few-shot manifests: K images per source from BOTH the target benchmark
and the WildGen training pool are mixed into the train set; the test set stays target-only
so the reported metric is comparable to the zero-shot/cross-benchmark numbers.
real_ratio controls the WildGen real anchor (real = real_ratio*K per WildGen source pooled).
target_real_ratio, if given, independently controls the target real anchor (real =
target_real_ratio*K per target source); this lets the target real distribution be aligned
with the WildGen real pool rather than left as a tiny fraction."""
trr = target_real_ratio if target_real_ratio is not None else real_ratio
tag = f"_tr{ratio_tag(trr)}" if target_real_ratio is not None and trr != real_ratio else ""
paths: dict[int, Path] = {}
for k in N_GRID:
sources = sorted(data)
if exclude_insufficient_k900 and k == 900:
sources = [s for s in sources if len(data[s]["fake"]) >= 1000 and len(data[s]["real"]) >= 900]
target_train: list[dict[str, Any]] = []
test_rows: list[dict[str, Any]] = []
source_summary: dict[str, dict[str, int]] = {}
for source in sources:
fake = sorted(data[source]["fake"], key=lambda p: stable_rank(seed, f"{name}:fake:{source}", p))
real = sorted(data[source]["real"], key=lambda p: stable_rank(seed, f"{name}:real:{source}", p))
fake_train_count = min(k, len(fake))
real_train_count = min(int(trr * fake_train_count), len(real))
target_train.extend(manifest_row(p, 1, source, name) for p in fake[:fake_train_count])
target_train.extend(manifest_row(p, 0, f"real:{source}", "real") for p in real[:real_train_count])
test_rows.extend(manifest_row(p, 1, source, name) for p in fake[fake_train_count:])
test_rows.extend(manifest_row(p, 0, f"real:{source}", "real") for p in real[real_train_count:])
source_summary[source] = {
"fake_total": len(fake),
"real_total": len(real),
"fake_train": fake_train_count,
"real_train": real_train_count,
"fake_test": max(0, len(fake) - fake_train_count),
"real_test": max(0, len(real) - real_train_count),
}
wildgen_rows = load_wildgen_balanced_rows(training_split, k, real_ratio)
train_rows = wildgen_rows + target_train
path = output_dir / "manifests" / f"{name}_joint{tag}_k{k}_realratio_{ratio_tag(real_ratio)}_seed{seed}.json"
write_json(
path,
{
"name": f"{name}_joint",
"k_per_source": k,
"real_ratio": real_ratio,
"target_real_ratio": trr,
"init": "warm_start",
"wildgen_train_rows": len(wildgen_rows),
"target_train_rows": len(target_train),
"sources": sources,
"source_summary": source_summary,
"train": train_rows,
"test": test_rows,
},
)
paths[k] = path
return paths
def main() -> None:
parser = argparse.ArgumentParser(description="Build the configured zero-shot and joint cross-benchmark manifests.")
parser.add_argument("--genimage-root", type=Path, required=True)
parser.add_argument("--forensynths-root", type=Path, required=True)
parser.add_argument("--training-split", type=Path, required=True)
parser.add_argument("--output-dir", type=Path, required=True)
parser.add_argument("--seed", type=int, default=42)
args = parser.parse_args()
summary = {"seed": args.seed, "target_real_ratio": 1.0, "datasets": {}}
for name, root, collect in [("genimage", args.genimage_root, collect_genimage), ("forensynths", args.forensynths_root, collect_forensynths)]:
data = collect(root)
if not data:
raise ValueError(f"No benchmark images found under {root}")
zero = build_external_manifests(name, data, args.seed, args.output_dir, exclude_insufficient_k900=(name == "forensynths"))
joint = build_joint_external_manifests(name, data, args.training_split, args.seed, args.output_dir, exclude_insufficient_k900=(name == "forensynths"), target_real_ratio=1.0)
summary["datasets"][name] = {"zero_shot": str(zero[0]), "joint": {str(k): str(v) for k, v in joint.items()}}
write_json(args.output_dir / "cross_benchmark_manifest_summary.json", summary)
print(json.dumps(summary, indent=2))
if __name__ == "__main__":
main()
|