File size: 20,688 Bytes
85805ad | 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 | """Shared helpers for the SID_Set data pipeline.
Deliberately dependency-light: numpy + pillow + pyarrow + huggingface_hub only.
scikit-learn / scipy / imagehash are NOT installed in the `techjam` env and must not be,
so logistic regression, ROC AUC, rank statistics and the pHash DCT are implemented here.
"""
from __future__ import annotations
import hashlib
import io
import json
import threading
import time
from collections import OrderedDict
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Iterator, Sequence
import numpy as np
import yaml
from PIL import Image
# Large synthetic images are legitimate here; disable the decompression-bomb guard.
Image.MAX_IMAGE_PIXELS = None
# --------------------------------------------------------------------------------------
# config / paths
# --------------------------------------------------------------------------------------
def project_root() -> Path:
"""Repo root = parent of src/."""
return Path(__file__).resolve().parent.parent
def load_config(path=None) -> dict:
path = Path(path) if path else project_root() / "configs" / "data.yaml"
with open(path, "r", encoding="utf-8") as fh:
cfg = yaml.safe_load(fh)
cfg["_root"] = str(project_root())
return cfg
def rpath(cfg: dict, *parts: str) -> Path:
"""Resolve a config-relative path against the project root."""
return Path(cfg["_root"]).joinpath(*parts)
def ensure_dir(p: Path) -> Path:
p.mkdir(parents=True, exist_ok=True)
return p
# --------------------------------------------------------------------------------------
# stable hashing
#
# Python's builtin hash() is salted per process (PYTHONHASHSEED), so a split derived from it
# silently changes between runs and between machines. That is an invisible train/test leak.
# Everything that must be reproducible goes through md5.
# --------------------------------------------------------------------------------------
def md5_int(*parts) -> int:
h = hashlib.md5("\x1f".join(str(p) for p in parts).encode("utf-8")).hexdigest()
return int(h, 16)
def md5_unit(*parts) -> float:
"""Deterministic float in [0, 1)."""
return (md5_int(*parts) % (1 << 53)) / float(1 << 53)
def md5_rng(*parts) -> np.random.Generator:
"""Deterministic numpy Generator keyed on content, not on call order."""
return np.random.default_rng(md5_int(*parts) % (1 << 63))
def md5_order_key(*parts) -> str:
"""Sort key giving a fixed pseudo-random permutation of any id set."""
return hashlib.md5("\x1f".join(str(p) for p in parts).encode("utf-8")).hexdigest()
# --------------------------------------------------------------------------------------
# image header probe (no pixel decode)
#
# CRITICAL: this must run on the RAW bytes. If the image is auto-decoded by `datasets`,
# img.format becomes None and img.quantization disappears, and the audit silently reports
# "no difference" when the difference is total.
# --------------------------------------------------------------------------------------
def probe_header(raw: bytes):
try:
im = Image.open(io.BytesIO(raw))
w, h = im.size
return {
"format": im.format or "UNKNOWN",
"mode": im.mode,
"width": int(w),
"height": int(h),
"n_bytes": len(raw),
"bytes_per_px": len(raw) / float(max(w * h, 1)),
"has_quant": int(bool(getattr(im, "quantization", None))),
}
except Exception:
return None
def decode_rgb(raw: bytes, allowed_modes=("RGB",)):
"""Decode to RGB, or None.
Modes outside `allowed_modes` are DROPPED, never converted: turning a greyscale image
into RGB fabricates a channel correlation that real colour photographs do not have, and
that fabrication would itself become a shortcut.
RGBA is the one exception worth allowing, and only when the alpha channel is fully
opaque -- then dropping it discards a constant channel and the RGB pixels are untouched.
It has to be opted into via config (`normalize.allowed_modes`), because v1 was built with
RGB only and rebuilding it must stay byte-identical.
"""
try:
im = Image.open(io.BytesIO(raw))
im.load()
if im.mode == "RGB":
return im
if im.mode == "RGBA" and "RGBA" in allowed_modes:
if np.asarray(im.split()[-1]).min() != 255:
return None # real transparency: the RGB under it is not meaningful
return im.convert("RGB")
return None
except Exception:
return None
# --------------------------------------------------------------------------------------
# rank statistics / ROC AUC / logistic regression (numpy only)
# --------------------------------------------------------------------------------------
def _average_ranks(x: np.ndarray) -> np.ndarray:
"""Equivalent of scipy.stats.rankdata(method="average"), without scipy."""
order = np.argsort(x, kind="mergesort")
ranks = np.empty(len(x), dtype=np.float64)
xs = x[order]
i = 0
while i < len(xs):
j = i
while j + 1 < len(xs) and xs[j + 1] == xs[i]:
j += 1
ranks[order[i:j + 1]] = 0.5 * (i + j) + 1.0
i = j + 1
return ranks
def roc_auc(y, score) -> float:
"""Mann-Whitney U form, exact under ties."""
y = np.asarray(y).astype(int)
score = np.asarray(score, dtype=np.float64)
n1 = int((y == 1).sum())
n0 = int((y == 0).sum())
if n1 == 0 or n0 == 0:
return float("nan")
r = _average_ranks(score)
return float((r[y == 1].sum() - n1 * (n1 + 1) / 2.0) / (n1 * n0))
def _sigmoid(z: np.ndarray) -> np.ndarray:
out = np.empty_like(z)
pos = z >= 0
out[pos] = 1.0 / (1.0 + np.exp(-z[pos]))
e = np.exp(z[~pos])
out[~pos] = e / (1.0 + e)
return out
def fit_logreg(X: np.ndarray, y: np.ndarray, l2: float = 1e-3, iters: int = 60) -> np.ndarray:
"""Newton / IRLS with ridge damping. X must NOT already contain an intercept column."""
n, d = X.shape
Xb = np.hstack([np.ones((n, 1)), X])
w = np.zeros(d + 1)
pen = np.eye(d + 1) * l2 * n
pen[0, 0] = 0.0 # never penalise the intercept
for _ in range(iters):
p = _sigmoid(Xb @ w)
g = Xb.T @ (p - y) + pen @ w
s = np.clip(p * (1 - p), 1e-8, None)
H = (Xb * s[:, None]).T @ Xb + pen
try:
step = np.linalg.solve(H, g)
except np.linalg.LinAlgError:
step = np.linalg.lstsq(H, g, rcond=None)[0]
w = w - step
if np.max(np.abs(step)) < 1e-9:
break
return w
def predict_logreg(w: np.ndarray, X: np.ndarray) -> np.ndarray:
return _sigmoid(np.hstack([np.ones((X.shape[0], 1)), X]) @ w)
def _standardize(train: np.ndarray, apply_to):
mu = train.mean(axis=0)
sd = train.std(axis=0)
sd[sd < 1e-12] = 1.0
return [(a - mu) / sd for a in apply_to]
def grouped_cv_auc(X, y, groups, folds: int = 5, l2: float = 1e-3, seed_tag: str = "cv") -> dict:
"""AUC of a logistic regression on `X`.
Folds are assigned by md5 of the group id (img_id), so the two crops of one photo can
never land on opposite sides of a fold boundary and inflate the score.
Returns both the in-sample AUC and the out-of-fold AUC; the out-of-fold one is the
number to report.
"""
X = np.asarray(X, dtype=np.float64)
y = np.asarray(y).astype(int)
fold_of = np.array([md5_int(seed_tag, g) % folds for g in groups])
(Xs,) = _standardize(X, [X])
w_full = fit_logreg(Xs, y, l2=l2)
in_sample = roc_auc(y, predict_logreg(w_full, Xs))
oof = np.full(len(y), np.nan)
for f in range(folds):
te = fold_of == f
tr = ~te
if te.sum() == 0 or len(np.unique(y[tr])) < 2:
continue
Xtr, Xte = _standardize(X[tr], [X[tr], X[te]])
w = fit_logreg(Xtr, y[tr], l2=l2)
oof[te] = predict_logreg(w, Xte)
ok = ~np.isnan(oof)
oof_auc = roc_auc(y[ok], oof[ok]) if ok.sum() else float("nan")
return {
"auc_in_sample": in_sample,
"auc_out_of_fold": oof_auc,
"n": int(len(y)),
"n_pos": int((y == 1).sum()),
"n_neg": int((y == 0).sum()),
"coef": w_full.tolist(),
}
def single_feature_auc(x, y) -> float:
"""AUC of one raw feature, sign-corrected. Shows which column carries the shortcut."""
a = roc_auc(y, np.asarray(x, dtype=np.float64))
return a if (a != a or a >= 0.5) else 1.0 - a
def percentiles(vals, qs=(10, 50, 90)) -> dict:
a = np.asarray(list(vals), dtype=np.float64)
if a.size == 0:
return {"p%d" % q: float("nan") for q in qs}
return {"p%d" % q: float(np.percentile(a, q)) for q in qs}
# --------------------------------------------------------------------------------------
# perceptual hash (DCT-II via a cosine basis matrix; scipy is unavailable)
# --------------------------------------------------------------------------------------
_DCT_CACHE = {}
def _dct_matrix(n: int) -> np.ndarray:
M = _DCT_CACHE.get(n)
if M is None:
k = np.arange(n).reshape(-1, 1)
i = np.arange(n).reshape(1, -1)
M = np.cos(np.pi * (2 * i + 1) * k / (2.0 * n))
M[0] *= 1.0 / np.sqrt(2.0)
M *= np.sqrt(2.0 / n)
_DCT_CACHE[n] = M
return M
def crop_and_encode(img: Image.Image, key, cfg: dict):
"""Normalize one source image into its crops. SHARED BY EVERY DATASET.
Both SID_Set and WildFake must go through this exact function. If the two datasets were
normalized by even slightly different code, the difference would itself become a
"which dataset is this" signal -- the confound the merge is most at risk from.
`key` is whatever identifies the image (img_id, or a zip member name); all randomness is
derived from it by md5, never from call order.
Returns [(crop_idx, crop_mode, jpeg_q, jpeg_bytes), ...].
"""
n = cfg["normalize"]
size = int(n["crop_size"])
modes = list(n["crop_modes"])
qmin, qmax = int(n["jpeg_quality_min"]), int(n["jpeg_quality_max"])
w, h = img.size
out = []
for k in range(int(n["crops_per_image"])):
mode = modes[k % len(modes)]
rng = md5_rng("crop", key, k)
if mode == "center":
x, y = (w - size) // 2, (h - size) // 2
else:
x = int(rng.integers(0, w - size + 1))
y = int(rng.integers(0, h - size + 1))
# Randomized quality, not fixed: reals arrive as JPEG (so they become double-JPEG)
# while synthetics arrive as PNG (single-JPEG). A fixed quality would turn that
# asymmetry into a fresh, equally learnable shortcut.
q = int(md5_rng("q", key, k).integers(qmin, qmax + 1))
buf = io.BytesIO()
img.crop((x, y, x + size, y + size)).save(
buf, "JPEG", quality=q, subsampling=int(n["jpeg_subsampling"]),
optimize=bool(n["jpeg_optimize"]))
out.append((k, mode, q, buf.getvalue()))
return out
def phash(img: Image.Image, dct_size: int = 32, bits: int = 8) -> int:
"""64-bit perceptual hash (bits=8 -> 8x8 low-frequency block, DC excluded from the median)."""
g = np.asarray(img.convert("L").resize((dct_size, dct_size), Image.Resampling.LANCZOS),
dtype=np.float64)
M = _dct_matrix(dct_size)
d = M @ g @ M.T
low = d[:bits, :bits]
med = np.median(low.flatten()[1:]) # drop the DC term before taking the median
h = 0
for v in low.flatten():
h = (h << 1) | int(v > med)
return h
def hamming(a: int, b: int) -> int:
return bin(a ^ b).count("1")
class PHashIndex:
"""Bucketed near-duplicate index, exact within `threshold` bits for 64-bit hashes.
The hash is split into (threshold + 1) bands; by pigeonhole, two hashes within
`threshold` bits must share at least one identical band. Band lookup therefore gives
exact recall with no O(n^2) scan.
"""
def __init__(self, threshold: int = 6, nbits: int = 64):
self.threshold = threshold
self.nbits = nbits
self.nbands = threshold + 1
self.width = (nbits + self.nbands - 1) // self.nbands
self.bands = [dict() for _ in range(self.nbands)]
self.n = 0
def _band_keys(self, h: int):
mask = (1 << self.width) - 1
return [(h >> (b * self.width)) & mask for b in range(self.nbands)]
def query(self, h: int):
"""Return a stored hash within `threshold` bits, or None."""
for b, key in enumerate(self._band_keys(h)):
for cand in self.bands[b].get(key, ()):
if hamming(cand, h) <= self.threshold:
return cand
return None
def add(self, h: int) -> None:
for b, key in enumerate(self._band_keys(h)):
self.bands[b].setdefault(key, []).append(h)
self.n += 1
def add_if_new(self, h: int) -> bool:
"""True if inserted (i.e. not a near-duplicate of anything already indexed)."""
if self.query(h) is not None:
return False
self.add(h)
return True
# --------------------------------------------------------------------------------------
# HuggingFace parquet access
#
# We do NOT use datasets(streaming=True): it walks shards in a fixed order and cannot skip a
# row group, so any filter still pays for every byte of the 140 GB. Reading the parquet files
# directly lets us (a) never request the `mask` column and (b) fetch only the row groups we
# selected. Either way nothing but the normalized crops is ever written to disk.
# --------------------------------------------------------------------------------------
@dataclass(frozen=True)
class RowGroupRef:
split: str # our split name: "train" | "val"
shard: str # e.g. data/validation-00000-of-00034.parquet
rg: int
n_rows: int
class SidSource:
def __init__(self, cfg: dict, verbose: bool = True):
self.cfg = cfg
self.repo = cfg["source"]["hf_repo"]
self.revision = cfg["source"].get("hf_revision", "main")
self.max_retries = int(cfg["source"]["max_retries"])
self.backoff = float(cfg["source"]["retry_backoff_s"])
self.verbose = verbose
self._fs = None
self._fs_lock = threading.Lock()
self._local = threading.local()
self.cache_dir = ensure_dir(rpath(cfg, cfg["paths"]["cache_dir"]))
# -- low level -------------------------------------------------------------------
@property
def fs(self):
if self._fs is None:
with self._fs_lock:
if self._fs is None:
from huggingface_hub import HfFileSystem
self._fs = HfFileSystem()
return self._fs
def _hf_path(self, shard: str) -> str:
return "datasets/%s@%s/%s" % (self.repo, self.revision, shard)
def _parquet_file(self, shard: str):
"""One ParquetFile per (thread, shard): HTTP file handles are not thread-safe."""
cache = getattr(self._local, "pf", None)
if cache is None:
cache = self._local.pf = OrderedDict()
if shard in cache:
return cache[shard]
import pyarrow.parquet as pq
pf = self._retry(lambda: pq.ParquetFile(self.fs.open(self._hf_path(shard), "rb")),
what="open " + shard)
cache[shard] = pf
while len(cache) > 4:
cache.popitem(last=False)
return pf
def _retry(self, fn: Callable, what: str = ""):
last = None
for attempt in range(self.max_retries):
try:
return fn()
except Exception as exc: # network flakiness is expected here
last = exc
if attempt + 1 < self.max_retries:
time.sleep(self.backoff * (2 ** attempt))
raise RuntimeError("failed after %d tries: %s: %s" % (self.max_retries, what, last))
# -- shard / row-group index ------------------------------------------------------
def list_shards(self, split: str):
hf_split = self.cfg["source"]["splits"][split]
from huggingface_hub import HfApi
info = self._retry(lambda: HfApi().dataset_info(self.repo, revision=self.revision),
what="dataset_info")
return sorted(s.rfilename for s in info.siblings
if s.rfilename.startswith("data/%s-" % hf_split)
and s.rfilename.endswith(".parquet"))
def row_group_index(self, split: str):
"""(shard, row_group, n_rows) for every row group in a split. Cached on disk."""
cache = self.cache_dir / ("rowgroups_%s.json" % split)
if cache.exists():
data = json.loads(cache.read_text(encoding="utf-8"))
return [RowGroupRef(split, d["shard"], d["rg"], d["n_rows"]) for d in data]
shards = self.list_shards(split)
if self.verbose:
print("[index] reading %d parquet footers for split=%s ..." % (len(shards), split))
def footer(shard: str):
md = self._parquet_file(shard).metadata
return [(shard, i, md.row_group(i).num_rows) for i in range(md.num_row_groups)]
out = []
with ThreadPoolExecutor(max_workers=int(self.cfg["source"]["index_workers"])) as ex:
for res in ex.map(footer, shards):
out.extend(RowGroupRef(split, s, i, n) for s, i, n in res)
cache.write_text(json.dumps([r.__dict__ for r in out]), encoding="utf-8")
if self.verbose:
print("[index] %d row groups, %d rows" % (len(out), sum(r.n_rows for r in out)))
return out
@staticmethod
def shuffled_row_groups(refs, tag: str = "rg"):
"""Fixed pseudo-random row-group order.
Row groups in SID_Set are class-interleaved (verified: roughly 1/3 per class inside
every row group of both splits), so taking whole row groups in md5 order is an
unbiased sample AND lets us skip the row groups we do not need.
"""
return sorted(refs, key=lambda r: md5_order_key(tag, r.shard, r.rg))
# -- data fetch -------------------------------------------------------------------
def read_row_group(self, ref: RowGroupRef, columns) -> list:
def _do():
tbl = self._parquet_file(ref.shard).read_row_group(ref.rg, columns=list(columns))
return tbl.to_pylist()
rows = self._retry(_do, what="read %s#%d" % (ref.shard, ref.rg))
for r in rows:
r["_shard"] = ref.shard
r["_rg"] = ref.rg
return rows
def iter_row_groups(self, refs, columns, workers=None, window=None) -> Iterator:
"""Fetch row groups in parallel but YIELD THEM IN `refs` ORDER.
Order matters: quota accounting downstream must not depend on which HTTP request
happened to finish first, or the selected sample silently changes between runs.
The bounded window keeps peak memory at roughly window * 56 MB.
"""
workers = workers or int(self.cfg["source"]["fetch_workers"])
window = window or int(self.cfg["source"]["prefetch_window"])
refs = list(refs)
ex = ThreadPoolExecutor(max_workers=workers)
try:
pending = OrderedDict()
nxt = 0
while nxt < min(window, len(refs)):
pending[nxt] = ex.submit(self.read_row_group, refs[nxt], columns)
nxt += 1
while pending:
idx = min(pending)
fut = pending.pop(idx)
yield refs[idx], fut.result()
if nxt < len(refs):
pending[nxt] = ex.submit(self.read_row_group, refs[nxt], columns)
nxt += 1
finally:
# The caller breaks out of this loop as soon as the quotas are full. Without
# cancel_futures, shutdown would block for a full prefetch window of downloads.
ex.shutdown(wait=False, cancel_futures=True)
# --------------------------------------------------------------------------------------
# small utilities
# --------------------------------------------------------------------------------------
def fmt_secs(s: float) -> str:
s = int(s)
if s >= 3600:
return "%dh%02dm%02ds" % (s // 3600, (s % 3600) // 60, s % 60)
return "%dm%02ds" % (s // 60, s % 60)
def label_bin(label_orig) -> int:
return int(int(label_orig) != 0)
|