"""Shared utilities for method Lightning modules. Every method has ~same optimizer / scheduler / metric logic; keep it DRY here. """ from __future__ import annotations import csv import os from pathlib import Path from typing import Any, Dict, List, Optional import pytorch_lightning as pl import torch import torch.distributed as dist import torch.nn.functional as F from torchmetrics.classification import BinaryAUROC, BinaryAccuracy try: from src.utils.fairness_metrics import compute_fairness_metrics, format_fairness_report _HAS_FAIRNESS = True except ImportError: _HAS_FAIRNESS = False class BaseMethod(pl.LightningModule): """Shared scaffolding: optimizer, scheduler, validation metrics.""" def __init__(self, method_cfg, backbone_cfg, data_cfg): super().__init__() self.save_hyperparameters(ignore=[]) self.method_cfg = method_cfg self.backbone_cfg = backbone_cfg self.data_cfg = data_cfg self.val_auc = BinaryAUROC() self.val_acc = BinaryAccuracy() self.test_auc = BinaryAUROC() self.test_acc = BinaryAccuracy() # --- per-sample prediction dump (populated during test_step) ------- # Each entry is a dict: {basename, video_path, generator, label, # score, pred}. Written out by on_test_epoch_end() on rank 0. self._test_pred_records: List[Dict[str, Any]] = [] # Snapshot of de-duplicated records saved by _dump_test_predictions for # use by _compute_and_log_fairness_metrics (called immediately after). self._last_test_records_for_fairness: List[Dict[str, Any]] = [] # Overall detection metrics saved in on_test_epoch_end for CSV export. self._last_test_acc: Optional[float] = None self._last_test_auc: Optional[float] = None # Optional output csv path; train.py may set this before trainer.test(). self.test_predictions_csv: Optional[str] = None # --- sub-classes implement ------------------------------------------------ def score(self, batch: Dict[str, Any]) -> torch.Tensor: """Return a (B,) tensor of 'fake-probability' scores in [0,1].""" raise NotImplementedError # --- lightning hooks ------------------------------------------------------ def validation_step(self, batch, batch_idx): if batch is None: return None scores = self.score(batch).detach() labels = batch["label"].long() self.val_auc.update(scores, labels) self.val_acc.update((scores > 0.5).int(), labels) return scores def on_validation_epoch_end(self): auc = self.val_auc.compute() acc = self.val_acc.compute() self.log("val/auc", auc, prog_bar=True, sync_dist=True) self.log("val/acc", acc, prog_bar=True, sync_dist=True) self.val_auc.reset(); self.val_acc.reset() def on_test_epoch_start(self): # Clear any stale records from a previous test run within the same # process (e.g. trainer.test() called multiple times). self._test_pred_records = [] self._last_test_records_for_fairness = [] self._last_test_acc = None self._last_test_auc = None def test_step(self, batch, batch_idx): if batch is None: return None scores = self.score(batch).detach() labels = batch["label"].long() self.test_auc.update(scores, labels) self.test_acc.update((scores > 0.5).int(), labels) # Collect per-sample predictions for CSV export. preds = (scores > 0.5).int() metas = batch.get("meta", None) scores_cpu = scores.detach().cpu().tolist() labels_cpu = labels.detach().cpu().tolist() preds_cpu = preds.detach().cpu().tolist() for i in range(len(scores_cpu)): m = metas[i] if (metas is not None and i < len(metas)) else {} self._test_pred_records.append({ "basename": str(m.get("basename", "")), "video_path": str(m.get("video_path", "")), "generator": str(m.get("generator", "")), "label": int(labels_cpu[i]), "score": float(scores_cpu[i]), "pred": int(preds_cpu[i]), }) return {"scores": scores, "labels": labels, "meta": metas} def on_test_epoch_end(self): auc = self.test_auc.compute() acc = self.test_acc.compute() self.log("test/auc", auc, sync_dist=True) self.log("test/acc", acc, sync_dist=True) # Save for CSV export alongside fairness metrics. self._last_test_auc = float(auc) self._last_test_acc = float(acc) self.test_auc.reset(); self.test_acc.reset() # --- dump per-sample predictions to CSV (rank 0) ------------------ self._dump_test_predictions() # --- compute fairness metrics (rank 0) ---------------------------- self._compute_and_log_fairness_metrics() def _dump_test_predictions(self) -> None: """Gather per-sample predictions across DDP ranks and write a CSV.""" records = list(self._test_pred_records) # Reset so subsequent test runs don't duplicate. self._test_pred_records = [] # DDP gather: each rank has its shard; rank 0 concatenates. if dist.is_available() and dist.is_initialized() and dist.get_world_size() > 1: world_size = dist.get_world_size() gathered: List[List[Dict[str, Any]]] = [None] * world_size # type: ignore try: dist.all_gather_object(gathered, records) except Exception: gathered = [records] if self.trainer is not None and not self.trainer.is_global_zero: return flat: List[Dict[str, Any]] = [] for shard in gathered: if shard: flat.extend(shard) records = flat else: if self.trainer is not None and not self.trainer.is_global_zero: return if not records: return # De-duplicate by (basename, generator) in case DDP padded samples. # NOTE: video_path is often empty in meta, so we use basename+generator # as the key. This correctly handles expand_fakes="all" where the same # basename appears once per generator. seen = set() unique: List[Dict[str, Any]] = [] for r in records: key = (r.get("basename", ""), r.get("generator", ""), r.get("video_path", "")) if key in seen: continue seen.add(key) unique.append(r) # Resolve output path. out_csv = self.test_predictions_csv if out_csv is None: # Fall back to /test_predictions.csv base_dir = None if self.trainer is not None and getattr(self.trainer, "log_dir", None): base_dir = self.trainer.log_dir if not base_dir: base_dir = os.getcwd() out_csv = str(Path(base_dir) / "test_predictions.csv") out_path = Path(out_csv) out_path.parent.mkdir(parents=True, exist_ok=True) fieldnames = ["basename", "video_path", "generator", "label", "pred", "score", "correct"] with open(out_path, "w", newline="") as f: writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader() for r in unique: r_out = { "basename": r.get("basename", ""), "video_path": r.get("video_path", ""), "generator": r.get("generator", ""), "label": r.get("label", ""), "pred": r.get("pred", ""), "score": f"{r.get('score', 0.0):.6f}", "correct": int(int(r.get("label", -1)) == int(r.get("pred", -2))), } writer.writerow(r_out) print(f"[test] wrote {len(unique)} per-sample predictions to {out_path}") # Save a snapshot for fairness metric computation (called right after). self._last_test_records_for_fairness = unique def _compute_and_log_fairness_metrics(self) -> None: """Compute group-fairness metrics using race4 annotations from test.csv.""" if not _HAS_FAIRNESS: return # Only rank 0 has the full records after _dump_test_predictions gathered them. if self.trainer is not None and not self.trainer.is_global_zero: return # Resolve annotations CSV path: prefer explicit cfg, fall back to data_cfg. annotations_csv: Optional[str] = None data_cfg = getattr(self, "data_cfg", None) if data_cfg is not None: # Try common config keys in order of preference. for key in ("fairness_annotations_csv", "test_annotations_csv", "annotations_csv"): val = getattr(data_cfg, key, None) if val: annotations_csv = str(val) break # Fall back: look for test.csv next to the data root. if annotations_csv is None: root = getattr(data_cfg, "root", None) if root: candidate = Path(root).parent / "test.csv" if candidate.exists(): annotations_csv = str(candidate) if annotations_csv is None or not Path(annotations_csv).exists(): # Last resort: check a well-known absolute path used in this project. fallback = Path("/apdcephfs_gy4/share_303628665/joywu/research/test.csv") if fallback.exists(): annotations_csv = str(fallback) if annotations_csv is None: print("[fairness] annotations CSV not found; skipping fairness metrics.") return # Re-read the records that were just written to CSV so we don't need # to keep them in memory. If the CSV path is known, read from it; # otherwise use the in-memory snapshot stored before _dump cleared it. records = getattr(self, "_last_test_records_for_fairness", []) if not records: print("[fairness] no prediction records available; skipping fairness metrics.") return metrics = compute_fairness_metrics( records, annotations_csv=annotations_csv, group_col="race4", ) if not metrics: return # Log scalar metrics to Lightning (shows up in TensorBoard / WandB). for key in ("F_FPR", "F_OAE", "F_DP", "F_MEO"): if key in metrics: self.log(f"test/{key}", metrics[key], sync_dist=False) # Print human-readable report. print(format_fairness_report(metrics, group_col="race4")) # Optionally write per-group breakdown to a CSV alongside predictions. self._dump_fairness_csv(metrics) def _dump_fairness_csv(self, metrics: Dict[str, Any]) -> None: """Write fairness breakdown + summary metrics to a single CSV file. The CSV has two sections separated by a blank line: Section 1 – per-group rows (one row per race4 group) Section 2 – summary rows: overall acc/auc + 4 fairness scalars Both sections use proper CSV rows (no comment lines). """ per_group = metrics.get("per_group", {}) if not per_group: return # Derive output path from test_predictions_csv. base_csv = self.test_predictions_csv if base_csv: out_path = Path(base_csv).with_name( Path(base_csv).stem + "_fairness.csv" ) else: base_dir = ( self.trainer.log_dir if (self.trainer and getattr(self.trainer, "log_dir", None)) else os.getcwd() ) out_path = Path(base_dir) / "test_fairness.csv" out_path.parent.mkdir(parents=True, exist_ok=True) import csv as _csv # ---- Section 1: per-group breakdown --------------------------------- pergroup_fields = ["section", "group", "n", "n_real", "n_fake", "acc", "fpr", "tpr", "tnr", "ppr", "npr"] # ---- Section 2: summary metrics ------------------------------------- summary_fields = ["section", "metric", "value"] # We write both sections into one file with a shared superset of columns. all_fields = ["section", "group", "n", "n_real", "n_fake", "acc", "fpr", "tpr", "tnr", "ppr", "npr", "metric", "value"] with open(out_path, "w", newline="") as f: writer = _csv.DictWriter(f, fieldnames=all_fields, extrasaction="ignore") writer.writeheader() # Per-group rows for g, stats in sorted(per_group.items()): writer.writerow({ "section": "per_group", "group": g, "n": stats["n"], "n_real": stats["n_real"], "n_fake": stats["n_fake"], "acc": f"{stats['acc']:.4f}", "fpr": f"{stats['fpr']:.4f}" if stats['fpr'] == stats['fpr'] else "nan", "tpr": f"{stats['tpr']:.4f}" if stats['tpr'] == stats['tpr'] else "nan", "tnr": f"{stats['tnr']:.4f}" if stats['tnr'] == stats['tnr'] else "nan", "ppr": f"{stats['ppr']:.4f}", "npr": f"{stats['npr']:.4f}", }) # Summary rows: overall detection metrics overall_acc = getattr(self, "_last_test_acc", None) overall_auc = getattr(self, "_last_test_auc", None) if overall_acc is not None: writer.writerow({"section": "summary", "metric": "overall_acc", "value": f"{overall_acc:.4f}"}) if overall_auc is not None: writer.writerow({"section": "summary", "metric": "overall_auc", "value": f"{overall_auc:.4f}"}) # Summary rows: 4 fairness scalars for key in ("F_FPR", "F_OAE", "F_DP", "F_MEO"): if key in metrics: writer.writerow({"section": "summary", "metric": key, "value": f"{metrics[key]:.4f}"}) print(f"[fairness] wrote per-group breakdown + summary to {out_path}") # --- optim ---------------------------------------------------------------- def configure_optimizers(self): cfg = self.method_cfg.optim params = [p for p in self.parameters() if p.requires_grad] optim = torch.optim.AdamW( params, lr=cfg.lr, weight_decay=cfg.weight_decay, ) sched = torch.optim.lr_scheduler.CosineAnnealingLR( optim, T_max=max(1, self.trainer.max_epochs - cfg.warmup_epochs), ) # warmup wrapper def lr_lambda(epoch: int) -> float: if epoch < cfg.warmup_epochs: return (epoch + 1) / max(1, cfg.warmup_epochs) return 1.0 warm = torch.optim.lr_scheduler.LambdaLR(optim, lr_lambda) return { "optimizer": optim, "lr_scheduler": { "scheduler": torch.optim.lr_scheduler.ChainedScheduler([warm, sched]), "interval": "epoch", }, } def bce_from_logits(logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor: return F.binary_cross_entropy_with_logits( logits.squeeze(-1), labels.float(), )