fairtalking-second-work / scripts /analysis /trace_cta_training.py
huahua123313's picture
Add files using upload-large-folder tool
eea47ad verified
Raw
History Blame Contribute Delete
19.4 kB
"""Full CTA TRAINING-step trace — covers everything that's MISSING from
trace_cta_forward.py:
1. Constructs a mini-batch: 1 real + 1 fake from HDTF-paired (so they share
the same driving audio — the structural premise of CTA).
2. Walks through `predict_pairs()` exposing the cross-attention internals
(Q/K/V shapes, attention map shape) of f_{A→V} and f_{V→A}.
3. Computes ALL FIVE losses exactly as `CTALitModule.training_step` does:
loss_av (REAL-only, drives predictors + backbones)
loss_va (REAL-only, drives predictors + backbones)
loss_asym (BOTH, margin loss on the asymmetry score)
loss_cls (BOTH, BCE on classifier; L_AV/L_VA are detach()ed)
loss_aux (FAKE-paired, cross-generator asym consistency)
Each loss's value, sample-mask, gradient destination is logged.
4. Performs ONE backward step and reports which parameters received non-zero
gradients per loss — proving "predictor is trained on real ONLY",
"detach() blocks BCE → predictor", etc.
This is a debug / paper-figure-aid script; not used during training.
Usage:
/opt/conda/envs/pytorch/bin/python3 scripts/analysis/trace_cta_training.py \\
--ckpt outputs/cta_diffusion_combined_20260604_205145/checkpoints/epoch16-valauc1.0000.ckpt
"""
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 as nn
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 = "─" * 92
DHRULE = "═" * 92
def banner(title: str, level: int = 0):
print()
print(DHRULE if level == 0 else HRULE)
print(f" {title}")
print(DHRULE if level == 0 else HRULE)
def step(n, title):
print(f"\n ── Step {n}: {title} ".ljust(94, "─"))
def tprint(name, x, indent=2, more=""):
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}]")
if x.is_floating_point() or x.is_complex():
info += f" mean={x.float().mean().item():+.4f}"
else:
info += f" values={x.detach().cpu().tolist()[:8]}"
if x.requires_grad or x.grad_fn is not None:
info += " grad_fn=" + (type(x.grad_fn).__name__ if x.grad_fn else "(leaf,req)")
else:
info = f"{type(x).__name__} = {x}"
print(f"{sp}{name:30s} {info}")
if more:
print(f"{sp}{'':30s}{more}")
def explain(text, indent=4):
sp = " " * indent
wrapped = textwrap.fill(text, width=92 - indent,
initial_indent=sp, subsequent_indent=sp)
print(f"\033[2m{wrapped}\033[0m")
# ============================================================================
# Cross-attention introspection
# ============================================================================
def expose_cross_attention(predictor, src_tokens, tgt_tokens, name="f_AV"):
"""Run the predictor with a forward hook that captures the FIRST
decoder layer's cross-attention input/output. Prints Q/K/V shapes
and attention shape so the figure can show 'cross-attention' explicitly.
"""
captured = {}
layer0 = predictor.decoder.layers[0]
def hook(module, args, kwargs, output):
# nn.TransformerDecoderLayer's multihead_attn is the cross-attention.
# Its forward signature is (query, key, value, ...).
# We don't directly intercept multihead_attn here; instead, we
# capture the layer-level inputs.
captured["tgt"] = args[0] # query input to the cross-attn
captured["memory"] = args[1] # key/value memory (audio for f_AV)
if isinstance(output, tuple):
captured["out"] = output[0]
else:
captured["out"] = output
handle = layer0.register_forward_hook(hook, with_kwargs=True)
out = predictor(src_tokens=src_tokens, tgt_query=tgt_tokens)
handle.remove()
print(f" {name} cross-attention (first decoder layer):")
if "tgt" in captured:
tprint(f" query (= tgt projection)", captured["tgt"], indent=4)
tprint(f" key/value memory (= src)", captured["memory"], indent=4)
tprint(f" layer-0 output", captured["out"], indent=4)
n_heads = layer0.multihead_attn.num_heads
head_dim = layer0.multihead_attn.embed_dim // n_heads
print(f" n_heads={n_heads}, head_dim={head_dim}, depth={len(predictor.decoder.layers)} layers")
return out
# ============================================================================
# Sample loader (HDTF-paired, real & fake share audio)
# ============================================================================
def load_paired_inputs(hdtf_root, num, fake_gen,
num_frames=16, frame_stride=2, frame_size=224,
audio_seconds=2.56, audio_sample_rate=16000):
root = Path(hdtf_root)
rv = root / "Real" / f"{num}_Fake_HDTF.mp4"
fv = root / fake_gen / f"{num}_Fake_HDTF_{fake_gen}.mp4"
aw = root / "_audio" / "Real" / f"{num}_Fake_HDTF.wav"
for p in (rv, fv, aw):
if not p.exists():
raise SystemExit(f"missing: {p}")
real_video = load_video_clip(str(rv), num_frames, frame_stride, frame_size)
fake_video = load_video_clip(str(fv), num_frames, frame_stride, frame_size)
audio = load_audio_clip(str(aw), audio_seconds, audio_sample_rate)
return rv, fv, aw, real_video, fake_video, audio
# ============================================================================
# Helpers for backward-trace
# ============================================================================
def grad_summary(module, label, indent=4):
"""Walk all parameters, count how many have non-zero gradient (after
backward of one specific loss). Returns nothing; prints a compact line.
"""
nz, total, l2 = 0, 0, 0.0
for p in module.parameters():
total += 1
if p.grad is not None and p.requires_grad:
g = p.grad
if torch.any(g != 0):
nz += 1
l2 += g.detach().pow(2).sum().item()
sp = " " * indent
rms = (l2 ** 0.5)
print(f"{sp}{label:35s} {nz}/{total} params with non-zero grad "
f"||grad||₂ = {rms:8.4e}")
def zero_all_grads(model):
for p in model.parameters():
if p.grad is not None:
p.grad.zero_()
# ============================================================================
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")
p.add_argument("--fake_generator", default="AniPortrait")
return p.parse_args()
def main():
args = parse_args()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
banner("CTA TRAINING-STEP TRACE (forward + 5 losses + backward gradient routing)", 0)
print(f" ckpt: {args.ckpt}")
print(f" device: {device}")
# ---- model -----------------------------------------------------------
state = torch.load(args.ckpt, map_location="cpu")
hp = state.get("hyper_parameters", {})
if not hp:
raise SystemExit("ckpt missing hyper_parameters")
method_cfg = OmegaConf.create(hp["method_cfg"])
backbone_cfg = OmegaConf.create(hp["backbone_cfg"])
data_cfg = OmegaConf.create(hp["data_cfg"])
print()
print(f" loss weights: av={method_cfg.loss.av_weight} va={method_cfg.loss.va_weight} "
f"asym={method_cfg.loss.asym_weight} cls={method_cfg.loss.cls_weight} "
f"aux={method_cfg.aux_crossgen.weight} (aux enabled={method_cfg.aux_crossgen.enabled})")
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)
model.load_state_dict(sd, strict=False)
model.to(device)
# IMPORTANT: use eval() so dropout is OFF (gives real numerical values
# rather than NaNs). Gradients still flow normally — eval() only changes
# the behavior of dropout/BatchNorm, not autograd.
model.eval()
# Convenient handles to sub-modules for grad inspection
sub = {
"video_backbone": model.model.video,
"audio_backbone": model.model.audio,
"f_A→V predictor": model.model.av_pred,
"f_V→A predictor": model.model.va_pred,
"classifier head": model.model.cls,
}
# ---- inputs ----------------------------------------------------------
rv_path, fv_path, aw_path, real_video, fake_video, 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,
)
train_transform = build_video_transform(data_cfg.aug, training=True)
real_norm = train_transform(real_video)
fake_norm = train_transform(fake_video)
banner("INPUT BATCH (1 real + 1 fake)", 1)
print(f" real video: {rv_path}")
print(f" fake video: {fv_path}")
print(f" audio (real, shared by both samples): {aw_path}")
# batch the two samples together — order [real, fake], labels [0, 1]
video_batch = torch.stack([real_norm, fake_norm], dim=0).to(device)
audio_batch = torch.stack([audio, audio ], dim=0).to(device)
labels = torch.tensor([0, 1], dtype=torch.long, device=device)
tprint("video batch (B,T,3,H,W)", video_batch)
tprint("audio batch (B,S)", audio_batch)
tprint("labels (B,)", labels)
# =====================================================================
# FORWARD
# =====================================================================
banner("FORWARD (predict_pairs + cross-attention introspection)", 0)
step(1, "video backbone (VideoMAE)")
v = model.model.video(video_batch)
tprint("v.tokens (B,N,768)", v["tokens"])
tprint("v.pooled (B,768)", v["pooled"])
explain("Token grid: (16/2)·(224/16)² = 8 × 14 × 14 = 1568 spatiotemporal tokens.")
step(2, "audio backbone (Wav2Vec2)")
a = model.model.audio(audio_batch)
tprint("a.tokens (B,T_a,768)", a["tokens"])
tprint("a.pooled (B,768)", a["pooled"])
step(3, "cross-modal predictor f_{A→V} (audio → video manifold)")
explain("Cross-attention: query=projected v.tokens (target side), "
"key/value=projected a.tokens (source memory). Each video token "
"attends to ALL audio tokens to refine its prediction.")
v_pred = expose_cross_attention(model.model.av_pred, a["tokens"], v["tokens"], name="f_AV")
tprint("v_pred (B,N,768)", v_pred)
step(4, "cross-modal predictor f_{V→A} (video → audio manifold)")
a_pred = expose_cross_attention(model.model.va_pred, v["tokens"], a["tokens"], name="f_VA")
tprint("a_pred (B,T_a,768)", a_pred)
step(5, "per-sample MSE residuals L_AV and L_VA")
explain("Computed with reduction='none' then averaged over (token, channel), "
"so each sample gets its own scalar.")
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
print(f" L_AV per sample: {l_av.detach().tolist()}")
print(f" L_VA per sample: {l_va.detach().tolist()}")
print(f" asym per sample: {asym.detach().tolist()}")
print(f" ↳ index 0 = real, index 1 = fake")
# =====================================================================
# FIVE LOSSES
# =====================================================================
banner("FIVE LOSSES (mirror of CTALitModule.training_step)", 0)
is_real = (labels == 0).float() # [1, 0]
denom_r = is_real.sum().clamp(min=1.0)
print(f" is_real mask = {is_real.detach().tolist()} "
f"(1 means 'count this sample', 0 means 'mask out')")
# ---- loss_av / loss_va: REAL only, drives predictor + backbones ------
step(1, "loss_av = mean(L_AV | label==0) — REAL only")
explain("fake's contribution is multiplied by 0 ⇒ no gradient through "
"the A→V predictor for fake samples.")
loss_av = (l_av * is_real).sum() / denom_r
tprint("loss_av (scalar)", loss_av)
step(2, "loss_va = mean(L_VA | label==0) — REAL only")
loss_va = (l_va * is_real).sum() / denom_r
tprint("loss_va (scalar)", loss_va)
# ---- loss_asym: BOTH, margin pushes fake's asym below real's --------
step(3, "loss_asym = ReLU(asym_fake_mean − asym_real_mean) — BOTH (margin)")
explain("If fake's asym is already lower than real's (the desired ranking), "
"ReLU(·) = 0 ⇒ no gradient. Else it pushes them apart. "
"Weak signal (weight 0.5) so predictors don't collapse.")
asym_r = asym[labels == 0]
asym_f = asym[labels == 1]
loss_asym = F.relu(asym_f.mean() - asym_r.mean())
tprint("loss_asym (scalar)", loss_asym,
more=f"asym_r mean={asym_r.mean().item():+.4f}, asym_f mean={asym_f.mean().item():+.4f}")
# ---- loss_cls: BOTH, drives classifier + backbones (predictor detached) -----
step(4, "loss_cls = BCE(score, label) — BOTH; L_AV/L_VA detach()ed")
explain("`l_av.detach()` and `l_va.detach()` cut the gradient path "
"from BCE back into the predictors. The classifier head can use "
"the asym scalars as features but cannot rewrite them.")
logits = model.model.classify(
v["pooled"], a["pooled"],
l_av.detach(), # ← detach()
l_va.detach(), # ← detach()
)
print(f" logits per sample: {logits.detach().squeeze(-1).tolist()}")
print(f" scores per sample: {torch.sigmoid(logits.squeeze(-1)).detach().tolist()}")
loss_cls = F.binary_cross_entropy_with_logits(logits.squeeze(-1), labels.float())
tprint("loss_cls (scalar)", loss_cls)
# ---- loss_aux: only computable if alt_video exists in batch ----------
step(5, "loss_aux = MSE(asym, asym_alt_generator) — paired FAKEs only")
explain("This batch has no alt_video / alt_audio (HDTF-paired isn't dual-generator "
"paired). In real training a fake clip can be paired with the SAME identity's "
"fake from a different generator; loss_aux pushes their s_asym to be close, "
"yielding a generator-invariant signal. Here loss_aux = 0.")
loss_aux = asym.new_zeros([])
tprint("loss_aux (scalar; 0 because no alt batch)", loss_aux)
# ---- total ----------------------------------------------------------
step(6, "total = Σ wᵢ · lossᵢ")
total = (
method_cfg.loss.av_weight * loss_av +
method_cfg.loss.va_weight * loss_va +
method_cfg.loss.asym_weight * loss_asym +
method_cfg.loss.cls_weight * loss_cls +
method_cfg.aux_crossgen.weight * loss_aux
)
tprint("total loss (scalar)", total,
more=f"= {method_cfg.loss.av_weight}·loss_av + {method_cfg.loss.va_weight}·loss_va "
f"+ {method_cfg.loss.asym_weight}·loss_asym + {method_cfg.loss.cls_weight}·loss_cls "
f"+ {method_cfg.aux_crossgen.weight}·loss_aux")
# =====================================================================
# BACKWARD — one loss at a time, see who actually receives gradients
# =====================================================================
banner("BACKWARD GRADIENT ROUTING (one loss at a time, count non-zero gradients per submodule)", 0)
explain("For each individual loss, we zero all gradients, call .backward(retain_graph=True), "
"and report how many parameters in each submodule have non-zero grads. "
"This makes 'who is trained by what' explicit.")
individual_losses = [
("loss_av", loss_av, "real-only mse on A→V"),
("loss_va", loss_va, "real-only mse on V→A"),
("loss_asym", loss_asym, "margin between asym_fake and asym_real"),
("loss_cls", loss_cls, "BCE on classifier (detach() on l_av/l_va)"),
]
for nm, l, desc in individual_losses:
zero_all_grads(model)
if l.requires_grad and l.grad_fn is not None:
try:
l.backward(retain_graph=True)
except RuntimeError as e:
print(f"\n [{nm}] backward FAILED: {e}")
continue
print(f"\n [{nm:9s}] {desc}")
for label, m in sub.items():
grad_summary(m, label)
# =====================================================================
# FINAL SUMMARY TABLE
# =====================================================================
banner("F I N A L T A B L E (this is what you'd label on the framework figure)", 0)
print()
print(f" {'sample':<6s} {'L_AV':>10s} {'L_VA':>10s} {'asym':>10s} {'logit':>10s} {'score':>8s} {'label':>6s}")
print(f" {'──────':<6s} {'──────────':>10s} {'──────────':>10s} {'──────────':>10s} {'──────────':>10s} {'──────':>8s} {'──────':>6s}")
for i, name in enumerate(["real", "fake"]):
gt = "0 (real)" if i == 0 else "1 (fake)"
sc = torch.sigmoid(logits[i].squeeze()).item()
print(f" {name:<6s} {l_av[i].item():>10.5f} {l_va[i].item():>10.5f} "
f"{asym[i].item():>+10.5f} {logits[i].squeeze().item():>+10.4f} {sc:>8.4f} {gt:>6s}")
print()
print(f" loss decomposition this batch:")
print(f" loss_av = {loss_av.item():.6f}")
print(f" loss_va = {loss_va.item():.6f}")
print(f" loss_asym = {loss_asym.item():.6f}")
print(f" loss_cls = {loss_cls.item():.6f}")
print(f" loss_aux = {loss_aux.item():.6f}")
print(f" ─────────────────────")
print(f" total = {total.item():.6f}")
print()
if __name__ == "__main__":
main()