File size: 14,552 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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
"""Step-by-step forward trace of CTA — shows every tensor shape and key stat
as data flows from raw mp4/wav to the final fake-probability.

This is a DEBUG / DOCUMENTATION script:
  * NOT meant to be run as part of training/evaluation
  * Purpose: when you draw the framework figure, run this once and you'll
    see exactly what each box should contain (shape, dtype, range, semantic)
  * Picks two paired samples (1 real + 1 fake, same identity from HDTF-paird
    so they share driving audio) and runs CTA through them, printing every step

Usage:
    /opt/conda/envs/pytorch/bin/python3 scripts/analysis/trace_cta_forward.py \\
        --ckpt outputs/cta_diffusion_combined_20260604_205145/checkpoints/epoch16-valauc1.0000.ckpt

  Optional:
    --hdtf_root /path/to/HDTF-paird     # default: gy5 path
    --num 023                             # which basename_num to pick
    --fake_generator AniPortrait          # which fake gen to pair with the real

Output:
  * console: structured step-by-step printout (recommend `... | tee trace.log`)
  * NO files written
"""
from __future__ import annotations

import argparse
import os
import sys
import textwrap
from pathlib import Path

import numpy as np
import torch
import torch.nn.functional as F

# silence weights_only restriction
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 omegaconf import OmegaConf

from src.data.fairtalking_dataset import load_video_clip, load_audio_clip
from src.data.transforms import build_video_transform
from src.methods import build_method


# ============================================================================
# Pretty-print helpers
# ============================================================================
HRULE = "─" * 90
DHRULE = "═" * 90


def banner(title: str, level: int = 0):
    bar = DHRULE if level == 0 else HRULE
    print()
    print(bar)
    print(f"  {title}")
    print(bar)


def tprint(name: str, x, more: str = "", indent: int = 2):
    """Print a tensor's key stats: shape, dtype, range, mean, std."""
    sp = " " * indent
    if isinstance(x, torch.Tensor):
        info = (f"shape={tuple(x.shape)}  dtype={str(x.dtype).replace('torch.', '')}  "
                f"range=[{x.min().item():+.4f}, {x.max().item():+.4f}]  "
                f"mean={x.mean().item():+.4f}  std={x.std().item():+.4f}")
    elif isinstance(x, np.ndarray):
        info = (f"shape={x.shape}  dtype={x.dtype}  "
                f"range=[{x.min():+.4f}, {x.max():+.4f}]")
    elif isinstance(x, (int, float)):
        info = f"value={x}"
    else:
        info = f"{type(x).__name__}"
    head = f"{sp}{name:30s}"
    print(f"{head} {info}")
    if more:
        print(f"{sp}{'':30s}{more}")


def step(n: int, title: str):
    print(f"\n  ── Step {n}: {title} ".ljust(92, "─"))


def explain(text: str, indent: int = 4):
    sp = " " * indent
    wrapped = textwrap.fill(text, width=90 - indent,
                            initial_indent=sp, subsequent_indent=sp)
    print(f"\033[2m{wrapped}\033[0m")   # dim text


# ============================================================================
def parse_args():
    p = argparse.ArgumentParser()
    p.add_argument("--ckpt", default="outputs/cta_diffusion_combined_20260604_205145/checkpoints/epoch16-valauc1.0000.ckpt")
    p.add_argument("--hdtf_root", default="/apdcephfs_gy5/share_303628665/joyewu/HDTF-paird")
    p.add_argument("--num", default="033",
                   help="basename_num under HDTF-paird Real/<num>_Fake_HDTF.mp4")
    p.add_argument("--fake_generator", default="AniPortrait",
                   help="which generator to pair with the real video (must "
                        "exist under <hdtf_root>/<gen>/)")
    return p.parse_args()


def load_paired_inputs(hdtf_root: str, num: str, fake_gen: str,
                       num_frames: int = 16, frame_stride: int = 2,
                       frame_size: int = 224,
                       audio_seconds: float = 2.56,
                       audio_sample_rate: int = 16000):
    """Load (real_video, real_audio) and (fake_video, real_audio) tensors.
    HDTF-paired: real and fake share the SAME driving audio (key for CTA's
    'audio is real' story)."""
    root = Path(hdtf_root)
    real_vid = root / "Real" / f"{num}_Fake_HDTF.mp4"
    fake_vid = root / fake_gen / f"{num}_Fake_HDTF_{fake_gen}.mp4"
    audio_w = root / "_audio" / "Real" / f"{num}_Fake_HDTF.wav"
    if not real_vid.exists():
        raise SystemExit(f"missing real video: {real_vid}")
    if not fake_vid.exists():
        raise SystemExit(f"missing fake video: {fake_vid}")
    if not audio_w.exists():
        raise SystemExit(f"missing audio: {audio_w}")

    rv = load_video_clip(str(real_vid), num_frames, frame_stride, frame_size)
    fv = load_video_clip(str(fake_vid), num_frames, frame_stride, frame_size)
    a  = load_audio_clip(str(audio_w), audio_seconds, audio_sample_rate)

    return (real_vid, rv), (fake_vid, fv), (audio_w, a)


def trace_one(label: str, video_tensor, audio_tensor, model, eval_transform, device):
    """Run CTA forward on a single sample and print every step."""
    banner(f"  T R A C I N G   '{label.upper()}'   S A M P L E", level=0)

    # ---- Step 1: raw input ------------------------------------------------
    step(1, "RAW INPUT (load_video_clip / load_audio_clip)")
    explain("Video comes out of decord/pyav as a (T, 3, H, W) float tensor in [0, 1]. "
            "Audio is a 1-D waveform at 16 kHz, 2.56 s long → 40960 samples.")
    tprint("video_raw  (T,3,H,W) [0,1]", video_tensor)
    tprint("audio_raw  (S,)      float", audio_tensor)

    # ---- Step 2: eval transform (normalize) --------------------------------
    step(2, "EVAL TRANSFORM  (ImageNet-mean/std normalization, no augmentation)")
    explain("VideoTransform with training=False only normalizes; it does NOT crop or jitter. "
            "Output is (T, 3, H, W) with ~zero mean per channel.")
    video_norm = eval_transform(video_tensor)
    tprint("video_norm (T,3,H,W)", video_norm)

    # batch axis
    video_b = video_norm.unsqueeze(0).to(device)
    audio_b = audio_tensor.unsqueeze(0).to(device)

    # ---- Step 3: VideoMAE backbone ----------------------------------------
    step(3, "VIDEO BACKBONE  (VideoMAE-base, frozen 70%)")
    explain("VideoMAE patchifies the 16-frame clip with patch=16, tubelet=2 → "
            "(16/2) × (224/16) × (224/16) = 8 × 14 × 14 = 1568 tokens, each 768-d. "
            "Output: pooled (mean over tokens) and full token sequence.")
    with torch.no_grad():
        v = model.model.video(video_b)
    tprint("v.tokens (B,N,768)", v["tokens"])
    tprint("v.pooled (B,768)",  v["pooled"])

    # ---- Step 4: Wav2Vec2 backbone ----------------------------------------
    step(4, "AUDIO BACKBONE  (Wav2Vec2-base, frozen 80%)")
    explain("Wav2Vec2 outputs ~50 Hz tokens. 2.56 s → ~127 frames at 50 Hz → "
            "wav2vec2 hidden seq ~80 (subsampled). Each token is 768-d.")
    with torch.no_grad():
        a = model.model.audio(audio_b)
    tprint("a.tokens (B,T_a,768)", a["tokens"])
    tprint("a.pooled (B,768)",     a["pooled"])

    # ---- Step 5: A→V predictor --------------------------------------------
    step(5, "CROSS-MODAL PREDICTOR f_{A→V}  (Transformer Decoder × 4)")
    explain("src = a.tokens (audio); tgt_query = v.tokens (video). Predicts "
            "video token embeddings from audio. Teacher-forcing target = v.tokens. "
            "Output v_pred has SAME shape as v.tokens.")
    with torch.no_grad():
        v_pred = model.model.av_pred(src_tokens=a["tokens"], tgt_query=v["tokens"])
    tprint("v_pred (B,N,768)", v_pred)

    L_AV = F.mse_loss(v_pred, v["tokens"], reduction="none").mean(dim=[1, 2])
    tprint("L_AV  (B,)", L_AV,
           more="= mean of (v_pred - v.tokens)^2 over tokens & channels")

    # ---- Step 6: V→A predictor --------------------------------------------
    step(6, "CROSS-MODAL PREDICTOR f_{V→A}  (Transformer Decoder × 4)")
    explain("src = v.tokens; tgt_query = a.tokens. Predicts audio tokens from video. "
            "Output a_pred has SAME shape as a.tokens.")
    with torch.no_grad():
        a_pred = model.model.va_pred(src_tokens=v["tokens"], tgt_query=a["tokens"])
    tprint("a_pred (B,T_a,768)", a_pred)

    L_VA = F.mse_loss(a_pred, a["tokens"], reduction="none").mean(dim=[1, 2])
    tprint("L_VA  (B,)", L_VA,
           more="= mean of (a_pred - a.tokens)^2 over tokens & channels")

    # ---- Step 7: asymmetry score ------------------------------------------
    step(7, "ASYMMETRY SCORE")
    s_asym = L_VA - L_AV
    L_total = L_VA + L_AV
    tprint("s_asym  = L_VA - L_AV", s_asym,
           more="positive ⇒ A→V easier (V→A harder); near-zero or negative ⇒ flat OOD")
    tprint("L_total = L_VA + L_AV", L_total,
           more="total prediction difficulty; helps classifier disambiguate easy/hard clips")

    # ---- Step 8: classifier head ------------------------------------------
    step(8, "CLASSIFIER HEAD  (MLP, 1538 → 256 → 1)")
    explain("Input is the concatenation of [v.pooled, a.pooled, s_asym, L_total] = "
            "(B, 768+768+1+1) = (B, 1538). The two scalars are detach()ed during "
            "training so BCE gradient cannot leak back into the predictors.")
    with torch.no_grad():
        feat = torch.cat([
            v["pooled"], a["pooled"],
            s_asym.unsqueeze(-1), L_total.unsqueeze(-1),
        ], dim=-1)
    tprint("classifier input (B,1538)", feat)
    with torch.no_grad():
        logit = model.model.cls(feat).squeeze(-1)
    tprint("logit (B,)", logit)
    score = torch.sigmoid(logit)
    tprint("score = sigmoid(logit) ∈ [0,1]", score,
           more="high score ⇒ fake")

    # ---- Step 9: summary --------------------------------------------------
    step(9, "SUMMARY  (one-liner you'd put in a figure caption)")
    print(f"      [{label}] score = {score.item():.4f}  "
          f"|  s_asym = {s_asym.item():+.4f}  "
          f"|  L_AV = {L_AV.item():.4f}  |  L_VA = {L_VA.item():.4f}")
    return {
        "label": label,
        "L_AV": float(L_AV.item()),
        "L_VA": float(L_VA.item()),
        "s_asym": float(s_asym.item()),
        "L_total": float(L_total.item()),
        "score": float(score.item()),
    }


# ============================================================================
def main():
    args = parse_args()
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    banner("CTA  forward-pass  trace", level=0)
    print(f"  ckpt  : {args.ckpt}")
    print(f"  HDTF  : {args.hdtf_root}")
    print(f"  num   : {args.num}")
    print(f"  fake  : {args.fake_generator}   (paired with real, SAME audio)")
    print(f"  device: {device}")

    # ---- model ------------------------------------------------------------
    state = torch.load(args.ckpt, map_location="cpu")
    hp = state.get("hyper_parameters", {})
    if not hp:
        raise SystemExit("ckpt has no hyper_parameters; cannot rebuild model")
    method_cfg = OmegaConf.create(hp["method_cfg"])
    backbone_cfg = OmegaConf.create(hp["backbone_cfg"])
    data_cfg = OmegaConf.create(hp["data_cfg"])

    print()
    print(f"  method.name            = {method_cfg.name}")
    print(f"  backbone.hf_id         = {backbone_cfg.hf_id}")
    print(f"  av_predictor.depth     = {method_cfg.av_predictor.depth}")
    print(f"  av_predictor.heads     = {method_cfg.av_predictor.heads}")
    print(f"  av_predictor.dropout   = {method_cfg.av_predictor.dropout}")
    print(f"  classifier.hidden      = {method_cfg.classifier.hidden}")
    print(f"  classifier.dropout     = {method_cfg.classifier.dropout}")

    model = build_method(
        method_name=method_cfg.name,
        method_cfg=method_cfg,
        backbone_cfg=backbone_cfg,
        data_cfg=data_cfg,
    )
    sd = state.get("state_dict", state)
    missing, unexpected = model.load_state_dict(sd, strict=False)
    print(f"  state_dict load: missing={len(missing)}  unexpected={len(unexpected)}")
    model.to(device).eval()

    eval_transform = build_video_transform(data_cfg.aug, training=False)

    # ---- load paired (real, fake) ----------------------------------------
    (real_path, real_video), (fake_path, fake_video), (audio_path, audio) = \
        load_paired_inputs(
            args.hdtf_root, args.num, args.fake_generator,
            num_frames=data_cfg.num_frames,
            frame_stride=data_cfg.frame_stride,
            frame_size=data_cfg.frame_size,
            audio_seconds=data_cfg.audio_seconds,
            audio_sample_rate=data_cfg.audio_sample_rate,
        )
    banner("INPUT FILES", level=1)
    print(f"    real video : {real_path}")
    print(f"    fake video : {fake_path}")
    print(f"    audio (real, shared by both):")
    print(f"                 {audio_path}")

    # ---- trace BOTH samples ----------------------------------------------
    real_summary = trace_one("real", real_video, audio,    model, eval_transform, device)
    fake_summary = trace_one("fake", fake_video, audio,    model, eval_transform, device)

    # ---- final comparison table ------------------------------------------
    banner("F I N A L   C O M P A R I S O N", level=0)
    print()
    print(f"    {'sample':<6s}  {'L_AV':>10s}  {'L_VA':>10s}  "
          f"{'s_asym':>10s}  {'L_total':>10s}  {'score':>8s}  {'label':>6s}")
    print(f"    {'─'*6:<6s}  {'─'*10:>10s}  {'─'*10:>10s}  "
          f"{'─'*10:>10s}  {'─'*10:>10s}  {'─'*8:>8s}  {'─'*6:>6s}")
    for s, gt in [(real_summary, "0 (real)"), (fake_summary, "1 (fake)")]:
        print(f"    {s['label']:<6s}  {s['L_AV']:>10.5f}  {s['L_VA']:>10.5f}  "
              f"{s['s_asym']:>+10.5f}  {s['L_total']:>10.5f}  {s['score']:>8.4f}  {gt:>6s}")

    print()
    diff_lav = fake_summary["L_AV"] / max(real_summary["L_AV"], 1e-12)
    diff_lva = fake_summary["L_VA"] / max(real_summary["L_VA"], 1e-12)
    print(f"    fake/real ratio:  L_AV ×{diff_lav:6.2f}     L_VA ×{diff_lva:6.2f}")
    print(f"    → fake video is OFF the predictor's learned real-manifold; "
          f"asymmetry score collapses toward 0 / goes negative.")
    print()


if __name__ == "__main__":
    main()