"""Token-level cross-modal residual heatmap (paper teaser figure). Source dataset: **HDTF-paird** (the only place where Real and Fake videos share the same driving audio, by the convention `_Fake_HDTF.mp4` in `Real/` and `_Fake_HDTF_.mp4` in each generator folder, with the same `` across folders). For a fixed identity-paired group (same ``, hence same driving audio across Real + 7 HDTF generators), this script: 1. Loads a CTA / CTA-ablation checkpoint. 2. For each of the 1+7 = 8 videos sharing that num, runs the predictors and computes the per-token MSE residual of the A->V predictor: r[t, p] = ||v_pred[t, p] - v_tokens[t, p]||^2 for p in patches 3. Reshapes that residual to the VideoMAE spatiotemporal grid (8 tubelet steps x 14 x 14 patches, for 16-frame 224x224 input with patch=16, tubelet=2). 4. Writes two figure styles per group: * `heatmap__overlay.png` — heatmap (jet) blended onto the original frames. Best for paper teaser figures. * `heatmap__pair.png` — original frames on top row, heatmap alone on bottom row. Best for supplementary "look more carefully" comparison. Layout: Each saved figure has 8 rows (Real + 7 fakes) x N_FRAMES columns. By default we sub-sample 4 frames per video for readability; +n_frames=... overrides. Usage ----- python3 scripts/analysis/dump_token_residual_heatmap.py \ +ckpt=outputs/cta_ablation_A1_full_20260602_153521/checkpoints/epoch10-valauc1.0000.ckpt \ method=cta_ablation method.ablation_variant=A1_full \ data=fairtalking \ +out_dir=outputs/analysis/heatmaps \ +num_groups=20 Optional overrides: +hdtf_root=/path/to/HDTF-paird # default uses HDTF_PAIRED_ROOT env or the on-disk HDTF-paird path. +basename_nums=[000,001,142] # explicit list, overrides num_groups +n_frames=4 # frames shown per video (default 4) +seed=0 # for random group selection NOTE: `data=...` is still required so the model can be built (it reads audio/video clip dimensions from the data config), but we DO NOT read mp4 paths from the FairTalking-Bench root — those Real/Fake videos do NOT share audio. HDTF-paird is the only paired source. Notes ----- * The script does NOT use the full DataLoader; it directly resolves video paths under the HDTF-paird root and loads them deterministically. * GPU recommended — CPU works but ~30s per group. """ from __future__ import annotations import os import random import sys from pathlib import Path from typing import Any, Dict, List, Optional import hydra import matplotlib.pyplot as plt import numpy as np import torch import torch.nn.functional as F from omegaconf import DictConfig, OmegaConf # --- 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 sys.path.insert(0, str(Path(__file__).resolve().parents[2])) from src.data.fairtalking_dataset import ( # noqa: E402 load_video_clip, load_audio_clip, ) from src.methods import build_method # noqa: E402 # VideoMAE-base on 16-frame 224x224 input: # patch=16 -> 14x14 spatial patches per frame group # tubelet=2 -> 16 frames -> 8 spatiotemporal steps # total tokens = 8 * 14 * 14 = 1568 TUBELET = 2 PATCH = 16 GRID_H = 224 // PATCH # 14 GRID_W = 224 // PATCH # 14 N_TUBELETS = 16 // TUBELET # 8 def _resolve_video_paths_hdtf(root: Path, num: str, generators: List[str]) -> Dict[str, Path]: """HDTF-paird layout (the only dataset where Real and Fake share audio): /Real/_Fake_HDTF.mp4 -> the real video //_Fake_HDTF_.mp4 -> fake from generator Same `` across folders <=> same driving audio across all videos in the group. Returns a dict {label: path}. Skips missing entries. """ paths: Dict[str, Path] = {} real = root / "Real" / f"{num}_Fake_HDTF.mp4" if real.exists(): paths["Real"] = real for g in generators: p = root / g / f"{num}_Fake_HDTF_{g}.mp4" if p.exists(): paths[g] = p return paths def _audio_path_hdtf(video_path: Path, root: Path, audio_cache_dir: Path) -> Path: """Mirror the mp4 tree under `_audio/`. e.g. /Real/000_Fake_HDTF.mp4 -> /Real/000_Fake_HDTF.wav /AniPortrait/000_Fake_HDTF_AniPortrait.mp4 -> /AniPortrait/000_Fake_HDTF_AniPortrait.wav """ rel = video_path.relative_to(root).with_suffix(".wav") return audio_cache_dir / rel def _load_pair(video_path: Path, audio_cache_dir: Path, num_frames: int, frame_stride: int, frame_size: int, audio_seconds: float, audio_sample_rate: int): video = load_video_clip(str(video_path), num_frames, frame_stride, frame_size) # NOTE: load_video_clip's internal resize gives (T, 3, H, W) float in [0,1]. # We need both the raw frames (for plotting) and the model-ready tensor. raw_frames = video.clone() # (T, 3, H, W) # Audio cache mirrors the mp4 tree: # /Real/_Fake_HDTF.mp4 ->