File size: 7,954 Bytes
1ef5ba8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""RADR: Reference-Anchored Diffusion Residual.

Hypothesis
----------
Pretrained generative video models (VideoMAE, SVD, CogVideoX) were trained
on billions of natural video frames. They embed a 'universal natural video
prior' that is NOT biased by FairTalking-Bench's three real-video sources.

For each input video we compute a reconstruction or inversion *residual*
against a frozen reference model. Fake videos generated by different
architectures than the reference (Sonic, Float, JoyVASA, etc.) will leave
systematic residual signatures that real videos do not.

Why this avoids the 'one-class on dataset real videos' trap
-----------------------------------------------------------
We never fit the reference model on FairTalking-Bench. The only trainable
parameters are a small classifier head on top of the residual. Quality
imbalance across CelebV-HQ / DFDC / HDTF does not contaminate the anchor.

Implementation (default path: VideoMAE)
---------------------------------------
1. Feed video through VideoMAE with high MAE mask ratio (0.75).
2. Read reconstruction logits vs. input patches; residual = |x - x_hat|.
3. Also keep decoder hidden features at multiple layers as 'residual
   statistics' (mean, var, higher moments over spatial-temporal dim).
4. MLP head -> BCE.

An optional heavier path uses Stable Video Diffusion DDIM-inversion;
stubbed out here; flip the cfg to 'svd' to enable. For first-round
training stick to VideoMAE — much faster and robust.
"""
from __future__ import annotations

from typing import Any, Dict

import torch
import torch.nn as nn
import torch.nn.functional as F

from .base import BaseMethod


class VideoMAEResidual(nn.Module):
    """Wraps VideoMAEForPreTraining to extract reconstruction residuals."""

    def __init__(self, hf_id: str, mask_ratio: float = 0.75):
        super().__init__()
        from transformers import VideoMAEForPreTraining
        self.model = VideoMAEForPreTraining.from_pretrained(hf_id)
        self.feature_dim = self.model.config.hidden_size
        self.decoder_dim = self.model.config.decoder_hidden_size
        self.mask_ratio = mask_ratio
        for p in self.model.parameters():
            p.requires_grad_(False)
        self.model.eval()

    @torch.no_grad()
    def forward(self, video: torch.Tensor) -> dict:
        """video: (B, T, 3, H, W) normalized for VideoMAE.
        Returns residual feature summary as a (B, D_feat) tensor."""
        B, T, C, H, W = video.shape
        # mask: deterministic per forward (no random seed shuffle per call)
        n_patches = (T // self.model.config.tubelet_size) \
            * (H // self.model.config.patch_size) \
            * (W // self.model.config.patch_size)
        n_masked = int(n_patches * self.mask_ratio)
        bool_masked_pos = torch.zeros((B, n_patches), dtype=torch.bool, device=video.device)
        # use first n_masked positions; deterministic
        bool_masked_pos[:, :n_masked] = True

        out = self.model(pixel_values=video, bool_masked_pos=bool_masked_pos)
        logits = out.logits                     # (B, n_masked, patch_dim)

        # ground-truth masked patches (normalized pixels)
        with torch.no_grad():
            patch_size = self.model.config.patch_size
            tub = self.model.config.tubelet_size
            # build patchified ground-truth (from model's patchify util)
            patchified = self._patchify(video, patch_size, tub)  # (B, n_patches, P*P*3*tub)
            target = patchified[bool_masked_pos].view(B, n_masked, -1)

        residual = logits - target               # (B, n_masked, patch_dim)

        # summary statistics per sample
        mean = residual.mean(dim=[1, 2])
        var = residual.var(dim=[1, 2])
        abs_mean = residual.abs().mean(dim=[1, 2])
        abs_max = residual.abs().amax(dim=[1, 2])
        l2_mean = residual.pow(2).mean(dim=[1, 2])
        # per-channel moments of final-layer decoder features
        summary = torch.stack([mean, var, abs_mean, abs_max, l2_mean], dim=-1)  # (B, 5)

        # also encoder pooled representation for extra info
        pooled = out.hidden_states[-1].mean(dim=1) if getattr(out, "hidden_states", None) is not None else residual.mean(dim=[1, 2]).unsqueeze(-1).expand(-1, self.feature_dim)

        return {"summary": summary, "pooled": pooled}

    @staticmethod
    def _patchify(video: torch.Tensor, patch_size: int, tubelet: int) -> torch.Tensor:
        """Replicate VideoMAE's patchification.  (B, T, 3, H, W) -> (B, N, P*P*3*tub)."""
        B, T, C, H, W = video.shape
        x = video.reshape(B, T // tubelet, tubelet, C, H, W)
        x = x.permute(0, 1, 4, 5, 2, 3, 6).contiguous() if False else x
        # simpler: unfold spatial
        x = video                                                 # (B, T, C, H, W)
        x = x.unfold(1, tubelet, tubelet)                          # (B, T', C, H, W, tub)
        x = x.unfold(3, patch_size, patch_size)                    # (B, T', C, H/P, W, tub, P)
        x = x.unfold(4, patch_size, patch_size)                    # (B, T', C, H/P, W/P, tub, P, P)
        x = x.permute(0, 1, 3, 4, 2, 5, 6, 7).contiguous()         # (B, T', Hp, Wp, C, tub, P, P)
        N = x.shape[1] * x.shape[2] * x.shape[3]
        patch_dim = C * tubelet * patch_size * patch_size
        return x.view(B, N, patch_dim)


class ResidualHead(nn.Module):
    def __init__(self, in_dim: int, hidden_dim: int, depth: int, dropout: float):
        super().__init__()
        layers = []
        d = in_dim
        for _ in range(depth):
            layers += [nn.Linear(d, hidden_dim), nn.GELU(), nn.Dropout(dropout)]
            d = hidden_dim
        self.mlp = nn.Sequential(*layers)
        self.out_dim = hidden_dim

    def forward(self, x): return self.mlp(x)


class RADRLitModule(BaseMethod):
    def __init__(self, method_cfg, backbone_cfg, data_cfg):
        super().__init__(method_cfg=method_cfg, backbone_cfg=backbone_cfg, data_cfg=data_cfg)
        assert method_cfg.anchor.type == "videomae", \
            "SVD path not implemented in the first round; set anchor.type=videomae"
        self.anchor = VideoMAEResidual(
            hf_id=method_cfg.anchor.hf_id,
            mask_ratio=method_cfg.anchor.mask_ratio,
        )
        in_dim = 5 + self.anchor.feature_dim
        self.head = ResidualHead(
            in_dim=in_dim,
            hidden_dim=method_cfg.residual_head.hidden_dim,
            depth=method_cfg.residual_head.depth,
            dropout=method_cfg.residual_head.dropout,
        )
        self.cls = nn.Sequential(
            nn.Linear(self.head.out_dim, method_cfg.classifier.hidden),
            nn.GELU(),
            nn.Dropout(method_cfg.classifier.dropout),
            nn.Linear(method_cfg.classifier.hidden, 1),
        )

    def _forward_logits(self, video: torch.Tensor) -> torch.Tensor:
        out = self.anchor(video)
        feat = torch.cat([out["summary"], out["pooled"]], dim=-1)
        h = self.head(feat)
        return self.cls(h)

    def training_step(self, batch, batch_idx):
        if batch is None:
            return None
        logits = self._forward_logits(batch["video"])
        labels = batch["label"].long()
        loss_cls = F.binary_cross_entropy_with_logits(
            logits.squeeze(-1), labels.float(),
        )
        # regularizer: keep head weights small so it has to use anchor signal
        reg = sum((p ** 2).sum() for p in self.head.parameters())
        loss = self.method_cfg.loss.cls_weight * loss_cls \
            + self.method_cfg.loss.residual_reg_weight * reg * 1e-6
        self.log_dict({
            "train/loss": loss, "train/loss_cls": loss_cls, "train/reg": reg,
        }, on_step=True, on_epoch=True, sync_dist=True)
        return loss

    @torch.no_grad()
    def score(self, batch: Dict[str, Any]) -> torch.Tensor:
        logits = self._forward_logits(batch["video"])
        return torch.sigmoid(logits.squeeze(-1))