| """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() |
|
|
| |
| |
| |
| self._test_pred_records: List[Dict[str, Any]] = [] |
| |
| |
| self._last_test_records_for_fairness: List[Dict[str, Any]] = [] |
| |
| self._last_test_acc: Optional[float] = None |
| self._last_test_auc: Optional[float] = None |
| |
| self.test_predictions_csv: Optional[str] = None |
|
|
| |
| def score(self, batch: Dict[str, Any]) -> torch.Tensor: |
| """Return a (B,) tensor of 'fake-probability' scores in [0,1].""" |
| raise NotImplementedError |
|
|
| |
| 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): |
| |
| |
| 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) |
|
|
| |
| 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) |
| |
| self._last_test_auc = float(auc) |
| self._last_test_acc = float(acc) |
| self.test_auc.reset(); self.test_acc.reset() |
|
|
| |
| self._dump_test_predictions() |
|
|
| |
| 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) |
| |
| self._test_pred_records = [] |
|
|
| |
| 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 |
| 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 |
|
|
| |
| |
| |
| |
| 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) |
|
|
| |
| out_csv = self.test_predictions_csv |
| if out_csv is None: |
| |
| 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}") |
|
|
| |
| 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 |
| |
| if self.trainer is not None and not self.trainer.is_global_zero: |
| return |
|
|
| |
| annotations_csv: Optional[str] = None |
| data_cfg = getattr(self, "data_cfg", None) |
| if data_cfg is not None: |
| |
| for key in ("fairness_annotations_csv", "test_annotations_csv", "annotations_csv"): |
| val = getattr(data_cfg, key, None) |
| if val: |
| annotations_csv = str(val) |
| break |
| |
| 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(): |
| |
| 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 |
|
|
| |
| |
| |
| 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 |
|
|
| |
| 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(format_fairness_report(metrics, group_col="race4")) |
|
|
| |
| 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 |
|
|
| |
| 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 |
|
|
| |
| pergroup_fields = ["section", "group", "n", "n_real", "n_fake", |
| "acc", "fpr", "tpr", "tnr", "ppr", "npr"] |
| |
| summary_fields = ["section", "metric", "value"] |
|
|
| |
| 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() |
|
|
| |
| 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}", |
| }) |
|
|
| |
| 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}"}) |
|
|
| |
| 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}") |
|
|
| |
| 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), |
| ) |
| |
| 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(), |
| ) |
|
|