fairtalking-second-work / scripts /analysis /ablation_swap_audio.py
huahua123313's picture
Add files using upload-large-folder tool
eea47ad verified
Raw
History Blame Contribute Delete
10.6 kB
"""Ablation-Swap: swap audio between different real identities and measure s_asym.
Motivation
----------
Our OOD-asymmetry claim says that s_asym < 0 on talking-head fakes because the
video is off-manifold while the audio stays in-distribution. To pressure-test
that account, this script constructs a "swap" ablation:
* both video and audio come from REAL clips
* but the audio is shuffled to belong to a DIFFERENT identity than the video
This puts the joint (v, a) pair off-manifold at the pairing level while each
marginal remains in-distribution. The predictor sees an ambiguous case that
is neither the "video-OOD" fake regime nor the fully in-distribution real
regime.
Prediction (falsifiable)
------------------------
If s_asym is genuinely tracking "which side is OOD", the swap distribution
should sit BETWEEN the real distribution (≈ 0) and the fake distribution
(≈ -0.23) — not indistinguishable from real.
Output
------
A .npz file with per-sample l_av, l_va, s_asym, score, label, meta, plus a
`condition` field ∈ {"real_paired", "real_swapped", "fake"} for downstream
plotting. Also emits a comparison histogram.
Run
---
Same hydra flags as dump_cta_features.py; example:
python3 scripts/analysis/ablation_swap_audio.py \
+ckpt=outputs/cta_ablation_diffusion_A1_full_20260611_161857/checkpoints/epoch02-valauc0.9999.ckpt \
method=cta_ablation method.ablation_variant=A1_full \
data=fairtalking +split=val \
+out_dir=outputs/analysis/ablation_swap_diffusion \
+seed=0
"""
from __future__ import annotations
import os
import sys
import warnings
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
# --- silence torch.load weights_only restriction (mirror src/train.py) -----
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
# ensure src/ is importable
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from src.data import FairTalkingDataModule # noqa: E402
from src.methods import build_method # noqa: E402
def _forward_batch(model, video, audio, device):
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
logits = model.model.classify(v["pooled"], a["pooled"], l_av, l_va)
score = torch.sigmoid(logits.squeeze(-1))
return (l_av.cpu().float().numpy(),
l_va.cpu().float().numpy(),
asym.cpu().float().numpy(),
score.cpu().float().numpy())
def _permute_audio_between_reals(audio: torch.Tensor, is_real: torch.Tensor,
rng: np.random.Generator) -> torch.Tensor:
"""Swap audio ONLY between real samples in the batch.
Fake samples keep their audio (we don't want to mutate the fake condition).
Real samples get their audio permuted with a derangement so that no real
sample retains its own audio.
"""
real_idx = torch.nonzero(is_real, as_tuple=False).squeeze(-1)
if real_idx.numel() < 2:
return audio # can't derange
order = np.arange(real_idx.numel())
for _ in range(20): # try up to 20 times to find a derangement
rng.shuffle(order)
if not np.any(order == np.arange(real_idx.numel())):
break
else:
# fall back to a rotation by 1
order = np.roll(np.arange(real_idx.numel()), 1)
swapped = audio.clone()
swapped[real_idx] = audio[real_idx[order]]
return swapped
@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=<path> override.")
ckpt_path = str(Path(ckpt_path).resolve())
out_dir = Path(cfg.get("out_dir", "outputs/analysis/ablation_swap")).resolve()
out_dir.mkdir(parents=True, exist_ok=True)
split = cfg.get("split", "val")
seed = int(cfg.get("seed", 0))
max_batches = cfg.get("max_batches", None)
max_batches = None if max_batches in (None, "null", "None") else int(max_batches)
print(f"[swap] ckpt = {ckpt_path}")
print(f"[swap] data cfg = {cfg.data.name}")
print(f"[swap] split = {split}")
print(f"[swap] out_dir = {out_dir}")
print(f"[swap] seed = {seed}")
model = build_method(
method_name=cfg.method.name,
method_cfg=cfg.method,
backbone_cfg=cfg.backbone,
data_cfg=cfg.data,
)
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"[swap] {len(missing)} missing keys (first 5): {missing[:5]}")
if unexpected: print(f"[swap] {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()
rng = np.random.default_rng(seed)
n_batches = len(loader) if max_batches is None else min(max_batches, len(loader))
print(f"[swap] forwarding {n_batches} batches (paired + swapped) …")
rows: List[Dict[str, Any]] = []
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))
is_real = (labels == 0)
# ---- pass 1: original pairing (real_paired + fake) --------------
l_av_o, l_va_o, asym_o, score_o = _forward_batch(model, video, audio, device)
# ---- pass 2: audio swapped among reals -------------------------
audio_sw = _permute_audio_between_reals(audio, is_real, rng)
l_av_s, l_va_s, asym_s, score_s = _forward_batch(model, video, audio_sw, device)
for i in range(video.size(0)):
m = metas[i] if isinstance(metas[i], dict) else {}
base = {
"basename": str(m.get("basename", "")),
"generator": str(m.get("generator", "")),
"num": str(m.get("num", "")),
"label": int(labels[i].item()),
}
# original condition
cond_orig = "real_paired" if is_real[i] else "fake"
rows.append({
**base,
"condition": cond_orig,
"l_av": float(l_av_o[i]),
"l_va": float(l_va_o[i]),
"asym": float(asym_o[i]),
"score": float(score_o[i]),
})
# swapped condition ONLY for real samples (fake pass-2 is redundant)
if is_real[i]:
rows.append({
**base,
"condition": "real_swapped",
"l_av": float(l_av_s[i]),
"l_va": float(l_va_s[i]),
"asym": float(asym_s[i]),
"score": float(score_s[i]),
})
if (bi + 1) % 20 == 0:
print(f"[swap] batch {bi+1}/{n_batches} collected {len(rows)} rows")
# ---- summary + save ----------------------------------------------------
import pandas as pd
df = pd.DataFrame(rows)
csv_path = out_dir / "swap_features.csv"
df.to_csv(csv_path, index=False)
print(f"[swap] wrote {csv_path} ({len(df)} rows)")
print("\n[swap] Per-condition summary")
for cond in ("real_paired", "real_swapped", "fake"):
sub = df[df["condition"] == cond]
if len(sub) == 0:
continue
print(f" {cond:<14} n={len(sub):4d} "
f"l_av={sub['l_av'].mean():.4f} "
f"l_va={sub['l_va'].mean():.4f} "
f"asym={sub['asym'].mean():+.4f} "
f"score={sub['score'].mean():.3f}")
# ---- histogram ---------------------------------------------------------
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
palette = {
"real_paired": ("#1E8449", "real (paired)"),
"real_swapped": ("#F1C40F", "real (audio-swapped)"),
"fake": ("#C0392B", "fake"),
}
fig, ax = plt.subplots(figsize=(7.6, 4.6))
all_asym = df["asym"].values
lo, hi = np.quantile(all_asym, 0.005), np.quantile(all_asym, 0.995)
bins = np.linspace(lo, hi, 55)
for cond, (color, label) in palette.items():
vals = df.loc[df["condition"] == cond, "asym"].values
if len(vals) == 0:
continue
ax.hist(vals, bins=bins, density=True, alpha=0.55,
color=color, label=f"{label} n={len(vals)} μ={vals.mean():+.3f}",
edgecolor="none")
ax.axvline(vals.mean(), color=color, lw=1.2, linestyle="--", alpha=0.9)
ax.set_xlabel(r"$s_{\rm asym}$ = $L_{V \to A}$ − $L_{A \to V}$")
ax.set_ylabel("density")
ax.set_title("Ablation-Swap: swapping audio between real identities")
ax.legend(loc="best", fontsize=9)
ax.grid(alpha=0.25, linestyle=":")
plt.tight_layout()
for ext in ("png", "pdf"):
p = out_dir / f"hist_asym_swap.{ext}"
plt.savefig(p, dpi=240, bbox_inches="tight", facecolor="white")
print(f"[swap] wrote {p}")
plt.close(fig)
if __name__ == "__main__":
main()