File size: 13,507 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
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
333
"""PSM: Phoneme-Synchrony Manifold.

Hypothesis
----------
Phonemes are physical instructions on the vocal tract. Articulation of /b/
requires bilabial closure, /f/ requires labiodental contact, etc. The
mapping { phoneme -> lip shape } is largely *speaker-independent*; the same
phoneme by different speakers yields similar lip shapes up to a small
identity-style variation.

If we learn an embedding space where (phoneme, lip_shape) pairs from REAL
videos lie on a compact manifold, then fake videos — whose generators
memorize audio->lip correlations but may violate the physical constraint
in subtle ways — will lie farther off-manifold on average.

Advantages over 'one-class real distribution learning'
------------------------------------------------------
We are NOT learning the full real joint. We are learning only the
*phoneme-conditional* distribution. Quality / domain differences across
CelebV-HQ / DFDC / HDTF mostly leak through identity and texture, not
through the phoneme-lip relation, so the conditional is far more robust.

Implementation
--------------
  phoneme feats: wav2vec2-lv-60-espeak-cv-ft  (CTC phoneme model, frozen)
  lip feats:     MediaPipe lip crop -> DINO ViT-S  (half trainable)
  projection head (MLP) -> 256-D manifold

Contrastive loss: anchor = phoneme token; positive = temporally-aligned
lip token; negatives = lip tokens from the same batch from other clips
AND a momentum memory bank.

Classifier: at inference we score the average per-frame (phoneme, lip)
compatibility. High compatibility => real; low => fake.
"""
from __future__ import annotations

from typing import Any, Dict, List, Optional

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

from .base import BaseMethod


# -----------------------------------------------------------------------------
# phoneme encoder (wav2vec2 frozen)
# -----------------------------------------------------------------------------
class PhonemeEncoder(nn.Module):
    def __init__(self, hf_id: str, freeze: bool = True):
        super().__init__()
        from transformers import Wav2Vec2Model
        self.model = Wav2Vec2Model.from_pretrained(hf_id)
        self.feature_dim = self.model.config.hidden_size
        if freeze:
            for p in self.model.parameters():
                p.requires_grad_(False)
            self.model.eval()

    def forward(self, wav: torch.Tensor) -> torch.Tensor:
        with torch.no_grad() if not any(p.requires_grad for p in self.model.parameters()) else torch.enable_grad():
            out = self.model(wav)
        return out.last_hidden_state       # (B, T_a, D)


# -----------------------------------------------------------------------------
# lip crop (MediaPipe lazily, CPU) + ViT image encoder
# -----------------------------------------------------------------------------
class MediaPipeLipCropper:
    """Run MediaPipe once per forward to get lip bbox per frame.

    Falls back to center crop if MediaPipe unavailable or no face found.
    Lazy-initialized per worker to be DataLoader-safe.
    """
    _LIP_LANDMARKS = [61, 146, 91, 181, 84, 17, 314, 405, 321, 375, 291,
                      308, 324, 318, 402, 317, 14, 87, 178, 88, 95]

    def __init__(self, output_size: int = 96):
        self.output_size = output_size
        self._mp = None

    def _ensure(self):
        if self._mp is None:
            try:
                import mediapipe as mp
                self._mp = mp.solutions.face_mesh.FaceMesh(
                    static_image_mode=False, max_num_faces=1, refine_landmarks=False,
                )
            except Exception:
                self._mp = False  # mark as unavailable

    def crop_frame(self, frame: np.ndarray) -> np.ndarray:
        """frame: (H, W, 3) uint8 RGB. Returns (out, out, 3) uint8 RGB."""
        self._ensure()
        H, W = frame.shape[:2]
        if self._mp is False:
            return self._center(frame)
        res = self._mp.process(frame)
        if not res.multi_face_landmarks:
            return self._center(frame)
        lm = res.multi_face_landmarks[0].landmark
        xs = np.array([lm[i].x for i in self._LIP_LANDMARKS]) * W
        ys = np.array([lm[i].y for i in self._LIP_LANDMARKS]) * H
        x0, x1 = xs.min(), xs.max(); y0, y1 = ys.min(), ys.max()
        cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
        # square, with some margin
        side = max(x1 - x0, y1 - y0) * 1.8
        x0 = int(max(0, cx - side / 2)); x1 = int(min(W, cx + side / 2))
        y0 = int(max(0, cy - side / 2)); y1 = int(min(H, cy + side / 2))
        crop = frame[y0:y1, x0:x1]
        if crop.size == 0:
            return self._center(frame)
        import cv2
        return cv2.resize(crop, (self.output_size, self.output_size))

    def _center(self, frame: np.ndarray) -> np.ndarray:
        import cv2
        H, W = frame.shape[:2]
        s = min(H, W) // 2
        cy, cx = H // 2, W // 2
        crop = frame[cy - s:cy + s, cx - s:cx + s]
        return cv2.resize(crop, (self.output_size, self.output_size))


class LipEncoder(nn.Module):
    """MediaPipe lip crop -> DINO ViT-S. Trainable top half."""

    def __init__(self, vit_hf_id: str, freeze_ratio: float = 0.5, lip_size: int = 96):
        super().__init__()
        from transformers import AutoModel
        self.vit = AutoModel.from_pretrained(vit_hf_id)
        self.feature_dim = self.vit.config.hidden_size
        self.lip_size = lip_size
        if freeze_ratio > 0:
            layers = self.vit.encoder.layer
            n = int(len(layers) * freeze_ratio)
            for layer in layers[:n]:
                for p in layer.parameters():
                    p.requires_grad_(False)

    def forward(self, lip_imgs: torch.Tensor) -> torch.Tensor:
        """lip_imgs: (B, T, 3, lip_size, lip_size) already normalized.
        Returns (B, T, D)."""
        B, T, C, H, W = lip_imgs.shape
        x = lip_imgs.reshape(B * T, C, H, W)
        # ViT expects 224; upsample if needed
        if H != 224:
            x = F.interpolate(x, size=(224, 224), mode="bilinear", align_corners=False)
        out = self.vit(pixel_values=x)
        tok = out.last_hidden_state[:, 0]   # CLS token
        return tok.view(B, T, -1)


# -----------------------------------------------------------------------------
# manifold projection + classifier
# -----------------------------------------------------------------------------
class ProjectionHead(nn.Module):
    def __init__(self, in_dim: int, out_dim: int):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(in_dim, in_dim), nn.GELU(), nn.Linear(in_dim, out_dim),
        )

    def forward(self, x): return F.normalize(self.net(x), dim=-1)


# -----------------------------------------------------------------------------
# Lightning module
# -----------------------------------------------------------------------------
class PSMLitModule(BaseMethod):
    def __init__(self, method_cfg, backbone_cfg, data_cfg):
        super().__init__(method_cfg=method_cfg, backbone_cfg=backbone_cfg, data_cfg=data_cfg)

        self.phoneme = PhonemeEncoder(
            hf_id=method_cfg.phoneme_encoder.hf_id,
            freeze=method_cfg.phoneme_encoder.freeze,
        )
        self.lip = LipEncoder(
            vit_hf_id=method_cfg.lip_encoder.vit_hf_id,
            freeze_ratio=method_cfg.lip_encoder.freeze_ratio,
        )

        pd = method_cfg.manifold.projection_dim
        self.proj_p = ProjectionHead(self.phoneme.feature_dim, pd)
        self.proj_l = ProjectionHead(self.lip.feature_dim, pd)

        # classifier on [compat, lip_pool, phon_pool]
        self.cls = nn.Sequential(
            nn.Linear(pd * 2 + 1, method_cfg.classifier.hidden),
            nn.GELU(),
            nn.Dropout(method_cfg.classifier.dropout),
            nn.Linear(method_cfg.classifier.hidden, 1),
        )

        self.register_buffer(
            "mem_bank",
            F.normalize(torch.randn(method_cfg.manifold.num_negatives, pd), dim=-1),
        )
        self.register_buffer("mem_ptr", torch.zeros(1, dtype=torch.long))

        # MediaPipe cropper runs on tensors in _prepare_lip_tensor below;
        # for simplicity we use center-crop in this initial version and
        # expose a hook to plug in MediaPipe at dataloader level.

    # ------------------------------------------------------------------
    @staticmethod
    def _resample_to_match(src: torch.Tensor, target_T: int) -> torch.Tensor:
        """Linear interpolation of token sequence along T dim."""
        B, T, D = src.shape
        x = src.transpose(1, 2)   # (B, D, T)
        x = F.interpolate(x, size=target_T, mode="linear", align_corners=False)
        return x.transpose(1, 2)  # (B, target_T, D)

    def _lip_from_video(self, video: torch.Tensor) -> torch.Tensor:
        """Produce lip crops from a normalized video tensor.

        Initial version: center crop the bottom-half of the frame (lip area
        heuristic). A more accurate version using MediaPipe runs in the
        dataloader; see TODO below.
        """
        B, T, C, H, W = video.shape
        # crop bottom half then rightmost 80% of width
        crop = video[..., H // 2:, :]
        # resize to 96 for lip encoder-friendly size
        crop = F.interpolate(
            crop.reshape(B * T, C, crop.shape[-2], crop.shape[-1]),
            size=(96, 96), mode="bilinear", align_corners=False,
        ).view(B, T, C, 96, 96)
        return crop

    # ------------------------------------------------------------------
    @torch.no_grad()
    def _enqueue(self, feats: torch.Tensor):
        K = self.mem_bank.size(0)
        n = feats.size(0)
        ptr = int(self.mem_ptr.item())
        if ptr + n > K:
            first = K - ptr
            self.mem_bank[ptr:] = feats[:first]
            self.mem_bank[:n - first] = feats[first:]
            self.mem_ptr[0] = (n - first) % K
        else:
            self.mem_bank[ptr:ptr + n] = feats
            self.mem_ptr[0] = (ptr + n) % K

    # ------------------------------------------------------------------
    def forward_feats(self, video, audio):
        ph = self.phoneme(audio)                 # (B, T_a, Dp)
        lip_imgs = self._lip_from_video(video)   # (B, T_v, 3, 96, 96)
        li = self.lip(lip_imgs)                  # (B, T_v, Dl)

        # resample phoneme to video's T
        T_v = li.shape[1]
        ph_r = self._resample_to_match(ph, T_v)

        zp = self.proj_p(ph_r)                   # (B, T_v, pd) unit
        zl = self.proj_l(li)
        return zp, zl

    # ------------------------------------------------------------------
    def _compatibility(self, zp, zl) -> torch.Tensor:
        """Per-sample mean cosine similarity between aligned phoneme & lip
        embeddings. Higher => more on-manifold => more real."""
        return (zp * zl).sum(dim=-1).mean(dim=1)   # (B,)

    def training_step(self, batch, batch_idx):
        if batch is None:
            return None
        video = batch["video"]; audio = batch["audio"]
        labels = batch["label"].long()

        zp, zl = self.forward_feats(video, audio)
        B, T, D = zp.shape
        zp_flat = zp.reshape(B * T, D)
        zl_flat = zl.reshape(B * T, D)

        # contrastive on REAL only
        is_real = (labels == 0)
        if is_real.any():
            rmask = is_real.unsqueeze(1).expand(-1, T).reshape(-1)
            zp_r = zp_flat[rmask]; zl_r = zl_flat[rmask]
            neg_bank = self.mem_bank                # (K, D)
            logits = torch.cat([
                (zp_r * zl_r).sum(-1, keepdim=True),        # positives
                zp_r @ neg_bank.t(),                         # negatives
            ], dim=1)                                         # (N, 1+K)
            logits = logits / self.method_cfg.manifold.temperature
            target = torch.zeros(logits.size(0), dtype=torch.long, device=logits.device)
            loss_con = F.cross_entropy(logits, target)
            with torch.no_grad():
                self._enqueue(zl_r.detach())
        else:
            loss_con = zp.new_zeros([])

        # consistency: neighbouring frames' compatibility should be smooth
        compat = (zp * zl).sum(dim=-1)            # (B, T)
        loss_cons = ((compat[:, 1:] - compat[:, :-1]) ** 2).mean()

        # classifier
        feat_cls = torch.cat([
            zp.mean(1), zl.mean(1), compat.mean(1, keepdim=True),
        ], dim=-1)
        logits_cls = self.cls(feat_cls)
        loss_cls = F.binary_cross_entropy_with_logits(
            logits_cls.squeeze(-1), labels.float(),
        )

        loss = (
            self.method_cfg.loss.contrastive_weight * loss_con
            + self.method_cfg.loss.consistency_weight * loss_cons
            + self.method_cfg.loss.cls_weight * loss_cls
        )

        self.log_dict({
            "train/loss": loss,
            "train/loss_con": loss_con,
            "train/loss_cons": loss_cons,
            "train/loss_cls": loss_cls,
        }, on_step=True, on_epoch=True, sync_dist=True)
        return loss

    @torch.no_grad()
    def score(self, batch: Dict[str, Any]) -> torch.Tensor:
        zp, zl = self.forward_feats(batch["video"], batch["audio"])
        compat = (zp * zl).sum(dim=-1)
        feat_cls = torch.cat([
            zp.mean(1), zl.mean(1), compat.mean(1, keepdim=True),
        ], dim=-1)
        logits = self.cls(feat_cls)
        return torch.sigmoid(logits.squeeze(-1))