File size: 9,780 Bytes
eea47ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
"""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

# --- 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


@hydra.main(version_base=None, config_path="../../configs", config_name="train")
def main(cfg: DictConfig) -> None:
    # ---- required runtime overrides ----------------------------------------
    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")  # "train" / "val" / "test"
    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)

    # ---- model + data -------------------------------------------------------
    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,
    )
    # In test-only configs (use_*_test), setup('fit') would crash; pick stage
    # based on requested split.
    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()

    # ---- forward + dump -----------------------------------------------------
    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))

            # The CTAModel / CTAAblationModel both expose predict_pairs that
            # returns (v, a, l_av, l_va, asym).  We ALSO need the raw token
            # residuals for t-SNE, so we re-do the forward here in-line.
            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"])

            # per-sample MSE (mean over tokens & channels)
            l_av = F.mse_loss(v_pred, v["tokens"], reduction="none").mean(dim=[1, 2])  # (B,)
            l_va = F.mse_loss(a_pred, a["tokens"], reduction="none").mean(dim=[1, 2])  # (B,)
            asym = l_va - l_av

            # residuals for t-SNE: per-sample mean of (target - pred) over tokens
            r_av = (v["tokens"] - v_pred).mean(dim=1)  # (B, vD)
            r_va = (a["tokens"] - a_pred).mean(dim=1)  # (B, aD)

            # classifier score
            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()