| """Robustness evaluation for CTA: in-memory perturb video frames at |
| inference time, recompute AUROC / AP / Acc / Acc@EER / fairness. |
| |
| Mirrors X-AVDT/train/evaluate_robustness.py (DeeperForensics-style 6 |
| frame-level perturbations × 5 levels), adapted to CTA's data layer: |
| |
| Input difference : CTA reads mp4 directly via decord/pyav (not pre-extracted .pt) |
| Perturbation point: between load_video_clip() and video_transform() |
| (i.e., on a (T, 3, H, W) float tensor in [0, 1]) |
| Audio : NEVER perturbed (consistent with CTA's "audio is real" framing) |
| |
| Perturbation set & level table copied verbatim from |
| /apdcephfs_gy4/share_303628665/joywu/research/X-AVDT/train/evaluate_robustness.py |
| to keep the comparison apples-to-apples. |
| |
| Output: |
| * console summary per (perturbation, level) |
| * append-only JSON to --save_json (one run per CLI invocation) |
| |
| Usage: |
| /opt/conda/envs/pytorch/bin/python scripts/analysis/evaluate_robustness.py \\ |
| --ckpt outputs/cta_diffusion_combined_20260604_205145/checkpoints/epoch16-valauc1.0000.ckpt \\ |
| --data fairtalking_diffusion_only \\ |
| --perturbation gaussian_noise --level 3 \\ |
| --save_json outputs/analysis/robustness/cta_runs.json |
| |
| Or run the whole sweep (6 × 5 = 30 settings) by wrapping in a loop: |
| for p in color_saturation color_contrast block_wise gaussian_noise gaussian_blur pixelate; do |
| for L in 1 2 3 4 5; do |
| python scripts/analysis/evaluate_robustness.py --ckpt ... --data ... \\ |
| --perturbation $p --level $L --save_json ... |
| done |
| done |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import collections |
| import csv as _csv |
| import json |
| import math |
| import os |
| import random as _rng_mod |
| import sys |
| import time |
| from pathlib import Path |
| from typing import Dict, List, Optional |
|
|
| import cv2 |
| import numpy as np |
| import torch |
| import torch.nn.functional as F |
| from omegaconf import OmegaConf |
| from sklearn.metrics import ( |
| accuracy_score, average_precision_score, classification_report, |
| confusion_matrix, roc_auc_score, roc_curve, |
| ) |
| from torch.utils.data import DataLoader |
| from tqdm import tqdm |
|
|
| |
| import lightning_fabric.utilities.cloud_io as _lf_cloud_io |
| _orig_torch_load = torch.load |
| def _unsafe_torch_load(*args, **kwargs): |
| kwargs["weights_only"] = False |
| return _orig_torch_load(*args, **kwargs) |
| _lf_cloud_io.torch.load = _unsafe_torch_load |
| torch.load = _unsafe_torch_load |
|
|
| sys.path.insert(0, str(Path(__file__).resolve().parents[2])) |
|
|
| from src.data import FairTalkingDataModule |
| from src.methods import build_method |
|
|
|
|
| |
| |
| |
| SEVERITY = { |
| "color_saturation": [1.0, 0.8, 1.2, 1.5, 2.0], |
| "color_contrast": [1.0, 0.85, 1.2, 1.4, 1.6], |
| "block_wise": [0, 8, 16, 24, 32], |
| "gaussian_noise": [0.0, 0.001, 0.005, 0.01, 0.05], |
| "gaussian_blur": [1, 3, 7, 11, 15], |
| "pixelate": [1, 2, 4, 6, 8], |
| "jpeg_quality": [100, 85, 70, 50, 30], |
| } |
| PERTURBATIONS = list(SEVERITY.keys()) |
| DEMO_DIMS = ("gender", "race4", "age_group") |
|
|
|
|
| |
| def _bgr2ycbcr(img_bgr): |
| img = img_bgr.astype(np.float32) / 255.0 |
| M = np.array([ |
| [ 0.299, 0.587, 0.114], |
| [-0.16874, -0.33126, 0.5], |
| [ 0.5, -0.41869, -0.08131], |
| ], dtype=np.float32) |
| yuv = img @ M.T |
| yuv[..., 1:] += 0.5 |
| return yuv |
|
|
|
|
| def _ycbcr2bgr(ycbcr): |
| yuv = ycbcr.copy() |
| yuv[..., 1:] -= 0.5 |
| M = np.array([ |
| [1.0, 0.0, 1.402], |
| [1.0, -0.34414, -0.71414], |
| [1.0, 1.772, 0.0], |
| ], dtype=np.float32) |
| bgr = yuv @ M.T |
| return np.clip(bgr * 255.0, 0, 255) |
|
|
|
|
| def _apply_color_saturation(frame_bgr, param): |
| if abs(param - 1.0) < 1e-6: |
| return frame_bgr |
| ycbcr = _bgr2ycbcr(frame_bgr) |
| ycbcr[:, :, 1] = 0.5 + (ycbcr[:, :, 1] - 0.5) * param |
| ycbcr[:, :, 2] = 0.5 + (ycbcr[:, :, 2] - 0.5) * param |
| out = _ycbcr2bgr(ycbcr) |
| return np.clip(out, 0, 255).astype(np.uint8) |
|
|
|
|
| def _apply_color_contrast(frame_bgr, param): |
| if abs(param - 1.0) < 1e-6: |
| return frame_bgr |
| out = frame_bgr.astype(np.float32) * param |
| return np.clip(out, 0, 255).astype(np.uint8) |
|
|
|
|
| def _apply_block_wise(frame_bgr, param, rng): |
| if param <= 0: |
| return frame_bgr |
| width = 8 |
| block = np.ones((width, width, 3), dtype=np.uint8) * 128 |
| n = max(1, min(frame_bgr.shape[0], frame_bgr.shape[1]) // 256 * int(param)) |
| out = frame_bgr.copy() |
| H, W = frame_bgr.shape[:2] |
| for _ in range(n): |
| rw = rng.randint(0, W - 1 - width) |
| rh = rng.randint(0, H - 1 - width) |
| out[rh:rh + width, rw:rw + width, :] = block |
| return out |
|
|
|
|
| def _apply_gaussian_noise(frame_bgr, param, rng_np): |
| if param <= 0: |
| return frame_bgr |
| ycbcr = _bgr2ycbcr(frame_bgr) |
| h, w, c = ycbcr.shape |
| noise = math.sqrt(param) * rng_np.standard_normal((h, w, c)).astype(np.float32) |
| noisy = ycbcr + noise |
| out = _ycbcr2bgr(noisy) |
| return np.clip(out, 0, 255).astype(np.uint8) |
|
|
|
|
| def _apply_gaussian_blur(frame_bgr, ksize): |
| ksize = int(ksize) |
| if ksize <= 1: |
| return frame_bgr |
| if ksize % 2 == 0: |
| ksize += 1 |
| sigma = ksize / 6.0 |
| return cv2.GaussianBlur(frame_bgr, (ksize, ksize), sigma) |
|
|
|
|
| def _apply_pixelate(frame_bgr, factor): |
| factor = int(factor) |
| if factor <= 1: |
| return frame_bgr |
| h, w = frame_bgr.shape[:2] |
| sw, sh = max(1, w // factor), max(1, h // factor) |
| small = cv2.resize(frame_bgr, (sw, sh), interpolation=cv2.INTER_AREA) |
| return cv2.resize(small, (w, h), interpolation=cv2.INTER_LINEAR) |
|
|
|
|
| def _apply_jpeg_quality(frame_bgr, quality): |
| """JPEG-encode then decode the BGR frame to simulate compression. |
| |
| quality is the JPEG quality factor in [1, 100]; higher = better quality |
| (less compression). 100 is effectively a no-op. |
| """ |
| quality = int(quality) |
| if quality >= 100: |
| return frame_bgr |
| quality = max(1, min(100, quality)) |
| encode_params = [int(cv2.IMWRITE_JPEG_QUALITY), quality] |
| ok, buf = cv2.imencode(".jpg", frame_bgr, encode_params) |
| if not ok: |
| return frame_bgr |
| decoded = cv2.imdecode(buf, cv2.IMREAD_COLOR) |
| return decoded if decoded is not None else frame_bgr |
|
|
|
|
| def perturb_video_tensor(video01: torch.Tensor, perturbation: str, level: int, |
| base_seed: int = 42) -> torch.Tensor: |
| """video01: (T, 3, H, W) float tensor in [0, 1]. Returns same shape/dtype. |
| |
| Internally: |
| 1) (T,3,H,W) float [0,1] -> (T,H,W,3) uint8 RGB |
| 2) Per frame: RGB->BGR, apply perturbation, BGR->RGB |
| 3) (T,H,W,3) uint8 RGB -> (T,3,H,W) float [0,1] |
| """ |
| if level == 1: |
| return video01 |
| param = SEVERITY[perturbation][level - 1] |
|
|
| seed = (hash((base_seed, perturbation, level)) & 0xFFFFFFFF) |
| py_rng = _rng_mod.Random(seed) |
| np_rng = np.random.RandomState(seed) |
|
|
| |
| arr = video01.detach().cpu().numpy() |
| arr = (arr * 255.0).clip(0, 255).astype(np.uint8) |
| arr = np.transpose(arr, (0, 2, 3, 1)) |
|
|
| out = np.empty_like(arr) |
| for t in range(arr.shape[0]): |
| bgr = cv2.cvtColor(arr[t], cv2.COLOR_RGB2BGR) |
| if perturbation == "color_saturation": |
| bgr = _apply_color_saturation(bgr, param) |
| elif perturbation == "color_contrast": |
| bgr = _apply_color_contrast(bgr, param) |
| elif perturbation == "block_wise": |
| bgr = _apply_block_wise(bgr, param, py_rng) |
| elif perturbation == "gaussian_noise": |
| bgr = _apply_gaussian_noise(bgr, param, np_rng) |
| elif perturbation == "gaussian_blur": |
| bgr = _apply_gaussian_blur(bgr, param) |
| elif perturbation == "pixelate": |
| bgr = _apply_pixelate(bgr, param) |
| elif perturbation == "jpeg_quality": |
| bgr = _apply_jpeg_quality(bgr, param) |
| else: |
| raise ValueError(f"unsupported perturbation: {perturbation}") |
| out[t] = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) |
|
|
| |
| out = np.transpose(out, (0, 3, 1, 2)) |
| return torch.from_numpy(out.astype(np.float32) / 255.0).to(video01.device) |
|
|
|
|
| |
| |
| |
| class PerturbedVideoTransform: |
| """Wrap an existing VideoTransform. Apply perturbation in [0,1] domain |
| first, then delegate to the underlying transform (which crops/normalizes).""" |
|
|
| def __init__(self, base_transform, perturbation: str, level: int, |
| base_seed: int = 42): |
| self.base = base_transform |
| self.perturbation = perturbation |
| self.level = level |
| self.base_seed = base_seed |
|
|
| def __call__(self, video): |
| if self.level != 1: |
| video = perturb_video_tensor( |
| video, self.perturbation, self.level, self.base_seed, |
| ) |
| if self.base is not None: |
| video = self.base(video) |
| return video |
|
|
|
|
| |
| |
| |
| def _tpr_at_fpr(y_true, y_score, fpr_target): |
| fpr, tpr, _ = roc_curve(y_true, y_score) |
| if (fpr <= fpr_target).any(): |
| return float(tpr[fpr <= fpr_target].max()) |
| return 0.0 |
|
|
|
|
| def _compute_eer_threshold(y_true, y_score): |
| fpr, tpr, thresholds = roc_curve(y_true, y_score) |
| fnr = 1 - tpr |
| return float(thresholds[int(np.argmin(np.abs(fpr - fnr)))]) |
|
|
|
|
| def _metrics_block(y_true, y_score, threshold=0.5): |
| y_true = np.asarray(y_true) |
| y_score = np.asarray(y_score) |
| y_pred = (y_score >= threshold).astype(int) |
|
|
| out = {} |
| try: out["AUROC"] = float(roc_auc_score(y_true, y_score)) |
| except: out["AUROC"] = None |
| try: out["AP"] = float(average_precision_score(y_true, y_score)) |
| except: out["AP"] = None |
| out[f"Accuracy@{threshold:.2f}"] = float(accuracy_score(y_true, y_pred)) |
| out["Confusion Matrix"] = confusion_matrix(y_true, y_pred, labels=[0, 1]).tolist() |
| out["Classification Report"] = classification_report( |
| y_true, y_pred, labels=[0, 1], output_dict=True, zero_division=0 |
| ) |
| try: |
| thr = _compute_eer_threshold(y_true, y_score) |
| out["EER_threshold"] = thr |
| out["Acc@EER"] = float(accuracy_score(y_true, (y_score >= thr).astype(int))) |
| except: |
| out["EER_threshold"] = None; out["Acc@EER"] = None |
| try: |
| out["TPR@FPR=1%"] = _tpr_at_fpr(y_true, y_score, 0.01) |
| out["TPR@FPR=0.1%"] = _tpr_at_fpr(y_true, y_score, 0.001) |
| except: |
| out["TPR@FPR=1%"] = None; out["TPR@FPR=0.1%"] = None |
| return out |
|
|
|
|
| def _fmt4(v): |
| try: return f"{float(v):.4f}" |
| except: return "n/a" |
|
|
|
|
| def compute_fairness(y_true, y_score, groups): |
| y_true = np.asarray(y_true); y_score = np.asarray(y_score); groups = np.asarray(groups) |
| pred = (y_score > 0.5).astype(int) |
| def _g_fpr(g): |
| m = (groups == g) & (y_true == 0); return float(pred[m].mean()) if m.sum() else 0.0 |
| def _g_tpr(g): |
| m = (groups == g) & (y_true == 1); return float(pred[m].mean()) if m.sum() else 0.0 |
| def _g_acc(g): |
| m = (groups == g); return float((pred[m] == y_true[m]).mean()) if m.sum() else 0.0 |
| def _g_dp(g): |
| m = (groups == g); return float(pred[m].mean()) if m.sum() else 0.0 |
| uniq = sorted(set(groups.tolist())) |
| if not uniq: |
| return None |
| fprs = [_g_fpr(g) for g in uniq] |
| tprs = [_g_tpr(g) for g in uniq] |
| accs = [_g_acc(g) for g in uniq] |
| dps = [_g_dp(g) for g in uniq] |
| ns = [int((groups == g).sum()) for g in uniq] |
| return { |
| "F_FPR": float(np.std(fprs)) * 100, |
| "F_MEO": (max(max(fprs) - min(fprs), max(tprs) - min(tprs))) * 100, |
| "F_DP": float(np.std(dps)) * 100, |
| "F_OAE": float(np.std(accs)) * 100, |
| "groups": {g: {"n": n, "fpr": f, "tpr": t, "acc": a, "dp": d} |
| for g, n, f, t, a, d in zip(uniq, ns, fprs, tprs, accs, dps)}, |
| } |
|
|
|
|
| def load_demographics(csv_path: Optional[str]) -> Dict[str, Dict[str, str]]: |
| if not csv_path or not os.path.exists(csv_path): |
| return {} |
| out = {} |
| with open(csv_path, newline="") as f: |
| for row in _csv.DictReader(f): |
| base = (row.get("basename") or "").strip() |
| if base: |
| out[base] = { |
| "gender": (row.get("gender") or "").strip(), |
| "race4": (row.get("race4") or "").strip(), |
| "age_group": (row.get("age_group") or "").strip(), |
| } |
| return out |
|
|
|
|
| def _set_seed(seed): |
| np.random.seed(seed); torch.manual_seed(seed); _rng_mod.seed(seed) |
| if torch.cuda.is_available(): |
| torch.cuda.manual_seed_all(seed) |
| torch.backends.cudnn.deterministic = True |
| torch.backends.cudnn.benchmark = False |
|
|
|
|
| |
| |
| |
| def parse_args(): |
| p = argparse.ArgumentParser() |
| p.add_argument("--ckpt", type=str, required=True) |
| p.add_argument("--data", type=str, default="fairtalking_diffusion_only", |
| help="hydra data config name (without .yaml)") |
| p.add_argument("--perturbation", type=str, required=True, choices=PERTURBATIONS) |
| p.add_argument("--level", type=int, required=True, choices=[1, 2, 3, 4, 5]) |
| p.add_argument("--batch_size", type=int, default=8) |
| p.add_argument("--num_workers", type=int, default=4) |
| p.add_argument("--seed", type=int, default=42) |
| p.add_argument("--demographics_csv", type=str, default=None, |
| help="optional CSV with basename,race4,gender,age_group " |
| "for fairness; if omitted, fairness section is skipped") |
| p.add_argument("--save_json", type=str, default=None) |
| p.add_argument("--verbose", action="store_true", |
| help="Also print per-fake-vs-real and fairness blocks to " |
| "stdout. JSON always contains them regardless.") |
| return p.parse_args() |
|
|
|
|
| def main(): |
| args = parse_args() |
| _set_seed(args.seed) |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
|
|
| |
| print(f"[robustness] ckpt: {args.ckpt}") |
| print(f"[robustness] data config: {args.data}") |
| print(f"[robustness] perturbation={args.perturbation} level={args.level} " |
| f"param={SEVERITY[args.perturbation][args.level - 1]}") |
|
|
| state = torch.load(args.ckpt, map_location="cpu") |
| hp = state.get("hyper_parameters", {}) |
| if not hp: |
| raise SystemExit("ckpt has no hyper_parameters; cannot rebuild model") |
| method_cfg = OmegaConf.create(hp["method_cfg"]) |
| backbone_cfg = OmegaConf.create(hp["backbone_cfg"]) |
|
|
| |
| data_cfg_path = Path("configs/data") / f"{args.data}.yaml" |
| if not data_cfg_path.exists(): |
| raise SystemExit(f"data config not found: {data_cfg_path}") |
| data_cfg = OmegaConf.load(data_cfg_path) |
| |
| os.environ.setdefault("DATA_ROOT", |
| "/apdcephfs_gy4/share_303628665/joywu/dataset/FairTalking-Bench") |
| os.environ.setdefault("HDTF_PAIRED_ROOT", |
| "/apdcephfs_gy5/share_303628665/joyewu/HDTF-paird") |
| os.environ.setdefault("MMDF_ROOT", |
| "/apdcephfs_gy4/share_303628665/joywu/dataset/MMDF_test_only") |
| data_cfg = OmegaConf.create(OmegaConf.to_container(data_cfg, resolve=True)) |
|
|
| |
| model = build_method( |
| method_name=method_cfg.name, |
| method_cfg=method_cfg, |
| backbone_cfg=backbone_cfg, |
| data_cfg=data_cfg, |
| ) |
| sd = state.get("state_dict", state) |
| missing, unexpected = model.load_state_dict(sd, strict=False) |
| if missing: print(f" missing keys: {len(missing)} (first 3: {missing[:3]})") |
| if unexpected: print(f" unexpected keys: {len(unexpected)}") |
| model.to(device).eval() |
|
|
| |
| dm = FairTalkingDataModule(data_cfg=data_cfg, return_paired=False) |
| base_eval_transform = dm.eval_transform |
| dm.eval_transform = PerturbedVideoTransform( |
| base_eval_transform, args.perturbation, args.level, args.seed, |
| ) |
| dm.setup(stage="test") |
| loader = DataLoader( |
| dm.test_ds, batch_size=args.batch_size, shuffle=False, |
| num_workers=args.num_workers, pin_memory=torch.cuda.is_available(), |
| collate_fn=getattr(dm, "_collate_fn", |
| __import__("src.data.datamodule", fromlist=["_collate_drop_none"])._collate_drop_none), |
| ) |
|
|
| |
| demographics = load_demographics(args.demographics_csv) |
|
|
| |
| scores, labels, basenames, generators = [], [], [], [] |
| with torch.inference_mode(): |
| for batch in tqdm(loader, desc=f"{args.perturbation}/L{args.level}", leave=False): |
| if batch is None: |
| continue |
| batch_video = batch["video"].to(device, dtype=torch.float) |
| batch_audio = batch["audio"].to(device, dtype=torch.float) |
| score = model.score({"video": batch_video, "audio": batch_audio}) |
| scores.extend(score.detach().cpu().float().numpy().tolist()) |
| labels.extend(batch["label"].long().tolist()) |
| metas = batch.get("meta", []) |
| for m in metas: |
| basenames.append(str((m or {}).get("basename", ""))) |
| generators.append(str((m or {}).get("generator", ""))) |
|
|
| |
| result = { |
| "perturbation": args.perturbation, |
| "level": args.level, |
| "param": SEVERITY[args.perturbation][args.level - 1], |
| "n_samples": len(scores), |
| } |
| o = _metrics_block(labels, scores) |
| o["Accuracy"] = o["Accuracy@0.50"] |
| result["overall"] = o |
|
|
| |
| real_idx = [i for i, y in enumerate(labels) if y == 0] |
| real_sc = [scores[i] for i in real_idx] |
| real_lab = [labels[i] for i in real_idx] |
| fake_gens = sorted({generators[i] for i, y in enumerate(labels) if y == 1 and generators[i]}) |
| per_fake = {} |
| for fm in fake_gens: |
| idxs = [i for i, (g, y) in enumerate(zip(generators, labels)) if g == fm and y == 1] |
| joint_sc = [scores[i] for i in idxs] + real_sc |
| joint_lab = [labels[i] for i in idxs] + real_lab |
| block = _metrics_block(joint_lab, joint_sc) |
| block["Accuracy"] = block["Accuracy@0.50"] |
| per_fake[fm] = block |
| result["per_fake_vs_real"] = per_fake |
|
|
| |
| fairness_overall = {} |
| if demographics: |
| for d in DEMO_DIMS: |
| groups = [demographics.get(b, {}).get(d, "") for b in basenames] |
| valid = [i for i, g in enumerate(groups) if g] |
| if not valid: |
| continue |
| fb = compute_fairness( |
| [labels[i] for i in valid], |
| [scores[i] for i in valid], |
| [groups[i] for i in valid], |
| ) |
| fairness_overall[d] = fb |
| result["fairness_overall"] = fairness_overall |
|
|
| |
| print(f"\n[{args.perturbation} L{args.level}] AUROC={_fmt4(o['AUROC'])} " |
| f"AP={_fmt4(o['AP'])} Acc={_fmt4(o['Accuracy'])} " |
| f"Acc@EER={_fmt4(o['Acc@EER'])} TPR@1%FPR={_fmt4(o['TPR@FPR=1%'])} " |
| f"TPR@0.1%FPR={_fmt4(o['TPR@FPR=0.1%'])} n={result['n_samples']}") |
| if args.verbose: |
| for fm, blk in per_fake.items(): |
| print(f" [{fm}+Real] AUROC={_fmt4(blk['AUROC'])} AP={_fmt4(blk['AP'])} " |
| f"Acc={_fmt4(blk['Accuracy'])} Acc@EER={_fmt4(blk['Acc@EER'])}") |
| for d in DEMO_DIMS: |
| fb = fairness_overall.get(d) |
| if fb: |
| print(f" fairness[{d}] F_FPR={fb['F_FPR']:.2f} F_MEO={fb['F_MEO']:.2f} " |
| f"F_DP={fb['F_DP']:.2f} F_OAE={fb['F_OAE']:.2f}") |
|
|
| |
| if args.save_json: |
| os.makedirs(os.path.dirname(args.save_json) or ".", exist_ok=True) |
| existing = [] |
| if os.path.exists(args.save_json): |
| try: |
| with open(args.save_json) as f: |
| blob = json.load(f) |
| existing = blob.get("runs", []) if isinstance(blob, dict) else [] |
| except Exception: |
| existing = [] |
| run = { |
| "ckpt": args.ckpt, |
| "saved_at": time.strftime("%Y-%m-%d %H:%M:%S"), |
| "data_config": args.data, |
| "demographics_csv": args.demographics_csv, |
| "seed": args.seed, |
| **result, |
| } |
| existing.append(run) |
| with open(args.save_json, "w") as f: |
| json.dump({"runs": existing}, f, indent=2, default=float) |
| print(f"\n>>> Appended run to {args.save_json}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|