fairtalking-second-work / scripts /analysis /dump_token_residual_heatmap.py
huahua123313's picture
Add files using upload-large-folder tool
eea47ad verified
Raw
History Blame Contribute Delete
21.9 kB
"""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 `<num>_Fake_HDTF.mp4` in
`Real/` and `<num>_Fake_HDTF_<Gen>.mp4` in each generator folder, with the
same `<num>` across folders).
For a fixed identity-paired group (same `<num>`, 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_<num>_overlay.png` — heatmap (jet) blended onto the original
frames. Best for paper teaser figures.
* `heatmap_<num>_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):
<root>/Real/<num>_Fake_HDTF.mp4 -> the real video
<root>/<Gen>/<num>_Fake_HDTF_<Gen>.mp4 -> fake from generator <Gen>
Same `<num>` 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.
<root>/Real/000_Fake_HDTF.mp4
-> <audio_cache>/Real/000_Fake_HDTF.wav
<root>/AniPortrait/000_Fake_HDTF_AniPortrait.mp4
-> <audio_cache>/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:
# <root>/Real/<num>_Fake_HDTF.mp4 -> <audio>/Real/<num>_Fake_HDTF.wav
# <root>/<Gen>/<num>_Fake_HDTF_<Gen>.mp4 -> <audio>/<Gen>/<...>.wav
apath = audio_cache_dir / video_path.parent.name / video_path.with_suffix(".wav").name
if apath.exists():
audio = load_audio_clip(str(apath), audio_seconds, audio_sample_rate)
else:
audio = torch.zeros(int(audio_seconds * audio_sample_rate))
return raw_frames, video, audio
def _per_token_residual(v_tokens: torch.Tensor, v_pred: torch.Tensor) -> np.ndarray:
"""Return (N_TUBELETS, GRID_H, GRID_W) residual heatmap (channel-mean MSE)."""
# v_tokens / v_pred: (1, 1568, 768)
r = (v_pred - v_tokens).pow(2).mean(dim=-1) # (1, 1568)
r = r.squeeze(0).reshape(N_TUBELETS, GRID_H, GRID_W).cpu().numpy()
return r
def _frame_to_image(frame: torch.Tensor) -> np.ndarray:
"""(3, H, W) float in [0,1] -> (H, W, 3) uint8."""
img = frame.detach().cpu().permute(1, 2, 0).numpy()
img = np.clip(img * 255.0, 0, 255).astype(np.uint8)
return img
def _upsample_heatmap(heatmap: np.ndarray, target_size: int = 224,
mode: str = "bilinear", sigma: float = 0.0) -> np.ndarray:
"""Upsample a coarse (GRID_H, GRID_W) heatmap to (target_size, target_size).
mode:
"nearest" — pixel-replication; preserves the visible token grid (the
blocky look we want for the most literal display).
"bilinear" — smooth interpolation between token centers; default,
standard saliency-visualization choice.
"bicubic" — slightly smoother than bilinear; rarely a meaningful
difference visually.
sigma:
Optional Gaussian blur applied AFTER upsampling, in pixels of the
target image (e.g. sigma=8 ≈ half a patch). Set 0 to disable.
"""
h = heatmap.astype(np.float32)
if mode == "nearest":
rep_h = target_size // heatmap.shape[0]
rep_w = target_size // heatmap.shape[1]
out = np.repeat(np.repeat(h, rep_h, axis=0), rep_w, axis=1)
else:
# Use torch's interpolate for bilinear / bicubic — no scipy dependency.
t = torch.from_numpy(h).unsqueeze(0).unsqueeze(0) # (1,1,gh,gw)
out = F.interpolate(t, size=(target_size, target_size),
mode=mode, align_corners=False).squeeze().numpy()
if sigma and sigma > 0:
# Lightweight separable Gaussian blur via torch (avoid scipy import).
radius = max(1, int(round(sigma * 3)))
kx = np.arange(-radius, radius + 1, dtype=np.float32)
kernel = np.exp(-(kx ** 2) / (2 * sigma ** 2))
kernel /= kernel.sum()
ker = torch.from_numpy(kernel).view(1, 1, 1, -1)
t = torch.from_numpy(out.astype(np.float32)).unsqueeze(0).unsqueeze(0)
# x-pass then y-pass
t = F.conv2d(t, ker, padding=(0, radius))
t = F.conv2d(t, ker.transpose(-1, -2), padding=(radius, 0))
out = t.squeeze().numpy()
return out
def _heatmap_to_rgba(heatmap: np.ndarray, vmin: float, vmax: float,
alpha: float = 0.55, mode: str = "bilinear",
sigma: float = 0.0):
"""(GRID_H, GRID_W) -> upsampled (224, 224, 4) RGBA in [0,1] for blending.
mode / sigma control the visual smoothness — see _upsample_heatmap.
"""
cmap = plt.get_cmap("jet")
up = _upsample_heatmap(heatmap, target_size=224, mode=mode, sigma=sigma)
norm = np.clip((up - vmin) / max(vmax - vmin, 1e-8), 0, 1)
rgba = cmap(norm) # (224, 224, 4)
rgba[..., 3] = norm * alpha # transparency follows magnitude
return rgba
def _save_overlay_figure(frames_per_label: Dict[str, np.ndarray],
heatmaps_per_label: Dict[str, np.ndarray],
frame_indices: List[int], out_path: Path,
num: str,
interp_mode: str = "bilinear",
sigma: float = 0.0,
alpha: float = 0.55) -> None:
"""Heatmap blended onto frames, 9 rows x len(frame_indices) cols."""
labels = list(frames_per_label.keys())
n_rows = len(labels)
n_cols = len(frame_indices)
# Use a global vmax so colors are comparable across panels.
all_h = np.concatenate([h.flatten() for h in heatmaps_per_label.values()])
vmin = float(np.percentile(all_h, 1))
vmax = float(np.percentile(all_h, 99))
fig, axes = plt.subplots(n_rows, n_cols,
figsize=(n_cols * 2.2, n_rows * 2.2))
if n_rows == 1:
axes = np.array([axes])
if n_cols == 1:
axes = axes.reshape(-1, 1)
for r, lab in enumerate(labels):
frames = frames_per_label[lab] # (T, H, W, 3) uint8
hmap = heatmaps_per_label[lab] # (N_TUBELETS, GRID_H, GRID_W)
for c, fi in enumerate(frame_indices):
ax = axes[r, c]
# The tubelet a frame belongs to:
tubelet_idx = min(fi // TUBELET, N_TUBELETS - 1)
base_img = frames[fi]
rgba = _heatmap_to_rgba(hmap[tubelet_idx], vmin, vmax,
alpha=alpha, mode=interp_mode, sigma=sigma)
ax.imshow(base_img)
ax.imshow(rgba)
ax.set_xticks([]); ax.set_yticks([])
for s in ax.spines.values():
s.set_visible(False)
if c == 0:
ax.set_ylabel(lab, fontsize=11, rotation=0, ha="right",
va="center", labelpad=10)
if r == 0:
ax.set_title(f"frame {fi}", fontsize=9)
fig.suptitle(f"A->V token residual (overlay) — basename_num={num} "
f"[interp={interp_mode}, sigma={sigma}, alpha={alpha}]",
fontsize=12)
fig.tight_layout(rect=(0.0, 0.0, 1.0, 0.97))
fig.savefig(out_path, dpi=200)
plt.close(fig)
print(f"[heatmap] wrote {out_path}")
def _save_pair_figure(frames_per_label: Dict[str, np.ndarray],
heatmaps_per_label: Dict[str, np.ndarray],
frame_indices: List[int], out_path: Path,
num: str,
interp_mode: str = "bilinear",
sigma: float = 0.0) -> None:
"""Two columns per video: left = original frame, right = heatmap alone.
9 rows × (len(frame_indices)*2) cols. Slightly wide but more inspectable."""
labels = list(frames_per_label.keys())
n_rows = len(labels)
n_pairs = len(frame_indices)
n_cols = n_pairs * 2
all_h = np.concatenate([h.flatten() for h in heatmaps_per_label.values()])
vmin = float(np.percentile(all_h, 1))
vmax = float(np.percentile(all_h, 99))
fig, axes = plt.subplots(n_rows, n_cols,
figsize=(n_cols * 1.6, n_rows * 1.8))
if n_rows == 1:
axes = np.array([axes])
if n_cols == 1:
axes = axes.reshape(-1, 1)
for r, lab in enumerate(labels):
frames = frames_per_label[lab]
hmap = heatmaps_per_label[lab]
for k, fi in enumerate(frame_indices):
tubelet_idx = min(fi // TUBELET, N_TUBELETS - 1)
ax_img = axes[r, 2 * k]
ax_h = axes[r, 2 * k + 1]
ax_img.imshow(frames[fi])
ax_img.set_xticks([]); ax_img.set_yticks([])
for s in ax_img.spines.values():
s.set_visible(False)
# Use the same upsampling settings as the overlay, so the two
# styles are visually consistent.
up = _upsample_heatmap(hmap[tubelet_idx], target_size=224,
mode=interp_mode, sigma=sigma)
ax_h.imshow(up, cmap="jet", vmin=vmin, vmax=vmax)
ax_h.set_xticks([]); ax_h.set_yticks([])
for s in ax_h.spines.values():
s.set_visible(False)
if k == 0 and r == 0:
ax_img.set_title("frame", fontsize=8)
ax_h.set_title("residual", fontsize=8)
elif r == 0:
ax_img.set_title(f"f{fi}", fontsize=8)
ax_h.set_title("res", fontsize=8)
if k == 0:
ax_img.set_ylabel(lab, fontsize=10, rotation=0, ha="right",
va="center", labelpad=8)
fig.suptitle(f"A->V token residual (frame | heatmap) — num={num} "
f"[interp={interp_mode}, sigma={sigma}]",
fontsize=11)
fig.tight_layout(rect=(0.0, 0.0, 1.0, 0.97))
fig.savefig(out_path, dpi=180)
plt.close(fig)
print(f"[heatmap] wrote {out_path}")
@hydra.main(version_base=None, config_path="../../configs", config_name="train")
def main(cfg: DictConfig) -> None:
# ---- args parsing -------------------------------------------------------
ckpt_path = cfg.get("ckpt", None)
if ckpt_path is None:
raise SystemExit(
"Missing +ckpt=... Example:\n"
" python3 scripts/analysis/dump_token_residual_heatmap.py \\\n"
" +ckpt=<...>.ckpt method=cta_ablation method.ablation_variant=A1_full \\\n"
" data=fairtalking +out_dir=outputs/analysis/heatmaps +num_groups=20"
)
ckpt_path = str(Path(ckpt_path).resolve())
out_dir = Path(cfg.get("out_dir", "outputs/analysis/heatmaps")).resolve()
out_dir.mkdir(parents=True, exist_ok=True)
seed = int(cfg.get("seed", 0))
n_frames = int(cfg.get("n_frames", 4))
num_groups = int(cfg.get("num_groups", 20))
# Visual smoothness controls — see _upsample_heatmap docstring.
interp_mode = str(cfg.get("heatmap_interp", "bilinear")) # nearest|bilinear|bicubic
sigma = float(cfg.get("heatmap_sigma", 0.0)) # post-upsample Gaussian blur, in image pixels
alpha = float(cfg.get("heatmap_alpha", 0.55)) # overlay transparency, 0..1
if interp_mode not in {"nearest", "bilinear", "bicubic"}:
raise SystemExit(
f"+heatmap_interp must be one of nearest|bilinear|bicubic, got {interp_mode!r}"
)
# Optional explicit list of basename_num values
explicit = cfg.get("basename_nums", None)
if explicit not in (None, "null", ""):
if isinstance(explicit, str):
explicit_list = [s.strip() for s in explicit.strip("[]").split(",") if s.strip()]
else:
explicit_list = [str(x).strip() for x in explicit]
nums_to_try = explicit_list
else:
nums_to_try = None
print(f"[heatmap] ckpt = {ckpt_path}")
print(f"[heatmap] data root = {cfg.data.root}")
print(f"[heatmap] out_dir = {out_dir}")
print(f"[heatmap] num_groups = {num_groups} (or explicit list: {nums_to_try})")
print(f"[heatmap] n_frames = {n_frames}")
print(f"[heatmap] interp/sigma/alpha = {interp_mode}/{sigma}/{alpha}")
# ---- model loading ------------------------------------------------------
model = build_method(
method_name=cfg.method.name,
method_cfg=cfg.method,
backbone_cfg=cfg.backbone,
data_cfg=cfg.data,
)
print("[heatmap] loading state_dict …")
state = torch.load(ckpt_path, map_location="cpu")
sd = state.get("state_dict", state)
model.load_state_dict(sd, strict=False)
device = "cuda" if torch.cuda.is_available() else "cpu"
model.to(device).eval()
# ---- discover candidate basename_num values (HDTF-paird layout) -------
# IMPORTANT: ours/FairTalking-Bench's Real and Fake do NOT share driving
# audio (different sources). Only HDTF-paird's Real and Fake share audio
# (same `<num>` in <root>/Real/ and <root>/<Gen>/). So we always read
# from the HDTF root for these heatmaps.
HDTF_ROOT_DEFAULT = "/apdcephfs_gy5/share_303628665/joyewu/HDTF-paird"
HDTF_GENERATORS = (
"AniPortrait", "Ditto", "EDTalk", "Float", "Hallo", "Joyvasa", "Sonic",
)
root = Path(
cfg.get("hdtf_root", os.environ.get("HDTF_PAIRED_ROOT", HDTF_ROOT_DEFAULT))
).resolve()
audio_cache_dir = Path(cfg.get("hdtf_audio_cache_dir",
str(root / "_audio"))).resolve()
hdtf_gens = list(cfg.get("hdtf_generators", HDTF_GENERATORS))
print(f"[heatmap] hdtf root = {root}")
print(f"[heatmap] hdtf audio = {audio_cache_dir}")
print(f"[heatmap] hdtf gens = {hdtf_gens}")
if not root.exists():
raise SystemExit(f"[heatmap] HDTF root not found: {root}\n"
" Pass +hdtf_root=/your/path or set HDTF_PAIRED_ROOT.")
if nums_to_try is None:
# All <num> for which Real/<num>_Fake_HDTF.mp4 exists. Sort, then sample.
real_dir = root / "Real"
all_nums = sorted({
p.name.split("_", 1)[0]
for p in real_dir.glob("*_Fake_HDTF.mp4")
})
rng = random.Random(seed)
rng.shuffle(all_nums)
nums_to_try = all_nums
# ---- iterate ------------------------------------------------------------
n_done = 0
n_skipped = 0
for num in nums_to_try:
if n_done >= num_groups and not explicit:
break
paths = _resolve_video_paths_hdtf(root, num, hdtf_gens)
if "Real" not in paths or len(paths) < 4:
n_skipped += 1
print(f"[heatmap] num={num}: only {len(paths)} videos found "
f"({sorted(paths)}); skipping")
continue
# Order: Real first, then generators in the requested order
ordered_labels = ["Real"] + [g for g in hdtf_gens if g in paths]
frames_per_label: Dict[str, np.ndarray] = {}
heatmaps_per_label: Dict[str, np.ndarray] = {}
try:
with torch.no_grad():
for lab in ordered_labels:
raw, vid, aud = _load_pair(
paths[lab], audio_cache_dir,
cfg.data.num_frames, cfg.data.frame_stride,
cfg.data.frame_size, cfg.data.audio_seconds,
cfg.data.audio_sample_rate,
)
vid_b = vid.unsqueeze(0).to(device) # (1, T, 3, H, W)
aud_b = aud.unsqueeze(0).to(device) # (1, S)
v = model.model.video(vid_b)
a = model.model.audio(aud_b)
v_pred = model.model.av_pred(
src_tokens=a["tokens"], tgt_query=v["tokens"]
)
r = _per_token_residual(v["tokens"], v_pred) # (8, 14, 14)
heatmaps_per_label[lab] = r
# store frames as uint8 RGB for plotting
frames_per_label[lab] = np.stack([
_frame_to_image(f) for f in raw
])
except Exception as e:
n_skipped += 1
print(f"[heatmap] num={num}: forward failed ({e}); skipping")
continue
# Pick frame indices uniformly across the 16 frames.
T = cfg.data.num_frames
frame_indices = np.linspace(0, T - 1, n_frames).astype(int).tolist()
# Save both styles
overlay_path = out_dir / f"heatmap_{num}_overlay.png"
pair_path = out_dir / f"heatmap_{num}_pair.png"
_save_overlay_figure(frames_per_label, heatmaps_per_label,
frame_indices, overlay_path, num,
interp_mode=interp_mode, sigma=sigma, alpha=alpha)
_save_pair_figure(frames_per_label, heatmaps_per_label,
frame_indices, pair_path, num,
interp_mode=interp_mode, sigma=sigma)
# Save per-video mean residual as a tiny csv summary too
summary_path = out_dir / f"heatmap_{num}_summary.csv"
with open(summary_path, "w") as f:
f.write("label,mean_residual,max_residual\n")
for lab in ordered_labels:
h = heatmaps_per_label[lab]
f.write(f"{lab},{h.mean():.6f},{h.max():.6f}\n")
n_done += 1
print(f"[heatmap] num={num}: produced 2 figures + summary "
f"({n_done}/{num_groups})")
print("")
print(f"[heatmap] DONE. produced={n_done}, skipped={n_skipped}")
print(f"[heatmap] outputs: {out_dir}")
if __name__ == "__main__":
main()