| """Dump per-sample CTA features for motivation analysis. |
| |
| Loads a trained CTA checkpoint, runs forward on a dataloader, and dumps |
| EVERY per-sample quantity needed for the motivation plots in PAPER_MOTIVATION.md: |
| |
| * `l_av` : (N,) MSE of A→V predictor |
| * `l_va` : (N,) MSE of V→A predictor |
| * `asym` : (N,) = l_va - l_av |
| * `score` : (N,) sigmoid(classifier logit), the model's fake probability |
| * `label` : (N,) 0=real, 1=fake |
| * `generator` : (N,) string, generator name ("" for real) |
| * `basename` : (N,) string id |
| * `r_av` : (N, vD) residual feature: mean over tokens of (v_tokens - v_pred) |
| * `r_va` : (N, aD) residual feature: mean over tokens of (a_tokens - a_pred) |
| |
| Output: a single .npz file you can `np.load` and pass to `visualize_motivation.py`. |
| |
| Usage |
| ----- |
| # NOTE: ckpt / out / split / max_batches are runtime fields not declared |
| # in configs/train.yaml, so they MUST be added with hydra's `+` prefix. |
| # Already-declared fields (method / data / ...) use plain `=`. |
| |
| python3 scripts/analysis/dump_cta_features.py \ |
| +ckpt=outputs/cta_ablation_A1_full_20260602_153521/checkpoints/epoch10-valauc1.0000.ckpt \ |
| method=cta_ablation \ |
| method.ablation_variant=A1_full \ |
| data=fairtalking \ |
| +split=val \ |
| +out=outputs/analysis/cta_features_oursval.npz \ |
| +max_batches=null |
| |
| Optional overrides: |
| method=cta_ablation method.ablation_variant=A1_full # for ablation ckpts |
| data=fairtalking_test_sadtalker +split=test # holdout family |
| |
| TIP: shell continuations with `\` must NOT have any character after the |
| backslash (not even a space) — otherwise the line is broken. The safest |
| form is to put everything on a single line. |
| |
| The script honors the standard hydra overrides used elsewhere in the project. |
| It assumes 1-GPU single-process inference (no DDP) — this analysis pass is |
| quick (<10 min for an entire test split) and DDP gather logic is not needed. |
| """ |
| from __future__ import annotations |
|
|
| import os |
| import sys |
| from pathlib import Path |
| from typing import Any, Dict, List |
|
|
| import hydra |
| import numpy as np |
| import torch |
| import torch.nn.functional as F |
| from omegaconf import DictConfig, OmegaConf |
| from torch.utils.data import DataLoader |
|
|
| |
| 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 |
|
|
|
|
| @hydra.main(version_base=None, config_path="../../configs", config_name="train") |
| def main(cfg: DictConfig) -> None: |
| |
| ckpt_path = cfg.get("ckpt", None) |
| if ckpt_path is None: |
| raise SystemExit( |
| "Missing `ckpt=...` override. Example:\n" |
| " python3 scripts/analysis/dump_cta_features.py \\\n" |
| " ckpt=outputs/.../epoch08-valauc1.0000.ckpt \\\n" |
| " data=fairtalking out=outputs/analysis/cta_features.npz" |
| ) |
| ckpt_path = str(Path(ckpt_path).resolve()) |
| out_path = Path(cfg.get("out", "outputs/analysis/cta_features.npz")).resolve() |
| out_path.parent.mkdir(parents=True, exist_ok=True) |
|
|
| split = cfg.get("split", "val") |
| if split not in {"train", "val", "test"}: |
| raise SystemExit(f"split must be train/val/test (got {split})") |
| max_batches = cfg.get("max_batches", None) |
| max_batches = None if max_batches in (None, "null", "None") else int(max_batches) |
|
|
| |
| print(f"[dump] ckpt = {ckpt_path}") |
| print(f"[dump] data config = {cfg.data.name}") |
| print(f"[dump] split = {split}") |
| print(f"[dump] out = {out_path}") |
| print(f"[dump] max_batches = {max_batches}") |
|
|
| model = build_method( |
| method_name=cfg.method.name, |
| method_cfg=cfg.method, |
| backbone_cfg=cfg.backbone, |
| data_cfg=cfg.data, |
| ) |
| print(f"[dump] loading state_dict from ckpt …") |
| state = torch.load(ckpt_path, map_location="cpu") |
| sd = state.get("state_dict", state) |
| missing, unexpected = model.load_state_dict(sd, strict=False) |
| if missing: |
| print(f"[dump] {len(missing)} missing keys (first 5): {missing[:5]}") |
| if unexpected: |
| print(f"[dump] {len(unexpected)} unexpected keys (first 5): {unexpected[:5]}") |
|
|
| device = "cuda" if torch.cuda.is_available() else "cpu" |
| model.to(device).eval() |
|
|
| dm = FairTalkingDataModule( |
| data_cfg=cfg.data, |
| return_paired=False, |
| ) |
| |
| |
| stage = "fit" if split in {"train", "val"} else "test" |
| dm.setup(stage=stage) |
|
|
| if split == "train": |
| loader = dm.train_dataloader() |
| elif split == "val": |
| loader = dm.val_dataloader() |
| else: |
| loader = dm.test_dataloader() |
|
|
| |
| L_AV: List[np.ndarray] = [] |
| L_VA: List[np.ndarray] = [] |
| ASYM: List[np.ndarray] = [] |
| SCORE: List[np.ndarray] = [] |
| LABEL: List[np.ndarray] = [] |
| GEN: List[str] = [] |
| BN: List[str] = [] |
| R_AV: List[np.ndarray] = [] |
| R_VA: List[np.ndarray] = [] |
|
|
| n_batches = len(loader) if max_batches is None else min(max_batches, len(loader)) |
| print(f"[dump] forwarding {n_batches} batches …") |
|
|
| with torch.no_grad(): |
| for bi, batch in enumerate(loader): |
| if batch is None: |
| continue |
| if max_batches is not None and bi >= max_batches: |
| break |
| video = batch["video"].to(device, non_blocking=True) |
| audio = batch["audio"].to(device, non_blocking=True) |
| labels = batch["label"].long() |
| metas = batch.get("meta", [{}] * video.size(0)) |
|
|
| |
| |
| |
| v = model.model.video(video) |
| a = model.model.audio(audio) |
| v_pred = model.model.av_pred(src_tokens=a["tokens"], tgt_query=v["tokens"]) |
| a_pred = model.model.va_pred(src_tokens=v["tokens"], tgt_query=a["tokens"]) |
|
|
| |
| l_av = F.mse_loss(v_pred, v["tokens"], reduction="none").mean(dim=[1, 2]) |
| l_va = F.mse_loss(a_pred, a["tokens"], reduction="none").mean(dim=[1, 2]) |
| asym = l_va - l_av |
|
|
| |
| r_av = (v["tokens"] - v_pred).mean(dim=1) |
| r_va = (a["tokens"] - a_pred).mean(dim=1) |
|
|
| |
| logits = model.model.classify(v["pooled"], a["pooled"], l_av, l_va) |
| score = torch.sigmoid(logits.squeeze(-1)) |
|
|
| L_AV.append(l_av.cpu().float().numpy()) |
| L_VA.append(l_va.cpu().float().numpy()) |
| ASYM.append(asym.cpu().float().numpy()) |
| SCORE.append(score.cpu().float().numpy()) |
| LABEL.append(labels.numpy().astype(np.int64)) |
| R_AV.append(r_av.cpu().float().numpy()) |
| R_VA.append(r_va.cpu().float().numpy()) |
| for m in metas: |
| GEN.append(str(m.get("generator", "")) if isinstance(m, dict) else "") |
| BN.append(str(m.get("basename", "")) if isinstance(m, dict) else "") |
|
|
| if (bi + 1) % 20 == 0: |
| print(f"[dump] batch {bi+1}/{n_batches} " |
| f"l_av≈{np.concatenate(L_AV).mean():.4f} " |
| f"l_va≈{np.concatenate(L_VA).mean():.4f}") |
|
|
| L_AV_arr = np.concatenate(L_AV) |
| L_VA_arr = np.concatenate(L_VA) |
| ASYM_arr = np.concatenate(ASYM) |
| SCORE_arr = np.concatenate(SCORE) |
| LABEL_arr = np.concatenate(LABEL) |
| R_AV_arr = np.concatenate(R_AV, axis=0) |
| R_VA_arr = np.concatenate(R_VA, axis=0) |
| GEN_arr = np.asarray(GEN, dtype=object) |
| BN_arr = np.asarray(BN, dtype=object) |
|
|
| print(f"[dump] collected {len(L_AV_arr)} samples") |
| print(f"[dump] reals = {(LABEL_arr == 0).sum()}, fakes = {(LABEL_arr == 1).sum()}") |
| print(f"[dump] l_av : mean(real)={L_AV_arr[LABEL_arr==0].mean():.4f} " |
| f"mean(fake)={L_AV_arr[LABEL_arr==1].mean():.4f}") |
| print(f"[dump] l_va : mean(real)={L_VA_arr[LABEL_arr==0].mean():.4f} " |
| f"mean(fake)={L_VA_arr[LABEL_arr==1].mean():.4f}") |
| print(f"[dump] asym : mean(real)={ASYM_arr[LABEL_arr==0].mean():.4f} " |
| f"mean(fake)={ASYM_arr[LABEL_arr==1].mean():.4f}") |
|
|
| np.savez_compressed( |
| out_path, |
| l_av=L_AV_arr, l_va=L_VA_arr, asym=ASYM_arr, |
| score=SCORE_arr, label=LABEL_arr, |
| generator=GEN_arr, basename=BN_arr, |
| r_av=R_AV_arr, r_va=R_VA_arr, |
| meta=np.array({ |
| "ckpt": ckpt_path, |
| "data_cfg": cfg.data.name, |
| "split": split, |
| "n_samples": int(len(L_AV_arr)), |
| }, dtype=object), |
| ) |
| print(f"[dump] wrote {out_path} ({out_path.stat().st_size/1e6:.1f} MB)") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|