"""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))