File size: 9,323 Bytes
a543540 441b0b6 | 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 | """
VideoMAELandmarkModel β Architecture for LSP Facial Expression Recognition.
Architecture (must match best_model.pth saved weights):
- LandmarkGCNEncoder : 2x GCNConv β Mamba (mambapy, n_layers=2) β (B, T, 96)
- CrossAttentionFusion: bidirectional cross-attention β (B, 1536)
- Classifier : 1536 β 512 β 128 β 14
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GCNConv, global_mean_pool
# ββ Mamba backend selection ββββββββββββββββββββββββββββββββββββββββββββββββββββ
# mambapy is pure Python and works on CPU (used during training).
# mamba_ssm is a CUDA-only fallback (rarely available on CPU HF Spaces).
# If neither is available, a GRU module is used as structural fallback;
# NOTE: GRU weights are not compatible with pre-trained Mamba weights β
# predictions will be wrong unless mambapy is installed.
_MAMBA_BACKEND = None
try:
from mambapy.mamba import Mamba as _MambaImpl, MambaConfig as _MambaCfg
_MAMBA_BACKEND = "mambapy"
except ImportError:
try:
from mamba_ssm import Mamba as _MambaSsmImpl
_MAMBA_BACKEND = "mamba_ssm"
except ImportError:
_MAMBA_BACKEND = "fallback"
print(f"[model] Mamba backend: {_MAMBA_BACKEND}")
class _GRUFallback(nn.Module):
"""GRU-based structural fallback when Mamba is unavailable.
WARNING: weights from pre-trained mambapy Mamba are NOT compatible.
Add 'mambapy' to requirements.txt for correct inference.
"""
def __init__(self, d_model: int, n_layers: int):
super().__init__()
self.gru = nn.GRU(d_model, d_model, num_layers=n_layers, batch_first=True)
def forward(self, x: torch.Tensor) -> torch.Tensor:
out, _ = self.gru(x)
return out
def _build_mamba(d_model: int = 96, d_state: int = 16,
d_conv: int = 4, expand: int = 2, n_layers: int = 2) -> nn.Module:
"""Instantiate a Mamba SSM using the best available backend."""
if _MAMBA_BACKEND == "mambapy":
cfg = _MambaCfg(
d_model=d_model, n_layers=n_layers,
d_state=d_state, d_conv=d_conv, expand_factor=expand,
)
return _MambaImpl(cfg)
if _MAMBA_BACKEND == "mamba_ssm":
layers = [
_MambaSsmImpl(d_model=d_model, d_state=d_state,
d_conv=d_conv, expand=expand)
for _ in range(n_layers)
]
return nn.Sequential(*layers)
# Structural fallback β incorrect weights, included for import compatibility
return _GRUFallback(d_model, n_layers)
# ββ LandmarkGCNEncoder βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class LandmarkGCNEncoder(nn.Module):
"""
Per-frame GCN (2 layers) + temporal Mamba SSM.
Input : list of T batched PyG graphs, each node feature shape (N, 3)
Output: (B, T, out_dim) β temporal landmark tokens
"""
def __init__(self, gcn_hidden: int = 48, out_dim: int = 96, dropout: float = 0.3):
super().__init__()
self.conv1 = GCNConv(3, gcn_hidden)
self.conv2 = GCNConv(gcn_hidden, gcn_hidden)
self.bn1 = nn.BatchNorm1d(gcn_hidden)
self.bn2 = nn.BatchNorm1d(gcn_hidden)
self.drop = nn.Dropout(dropout)
self.proj = nn.Sequential(
nn.Linear(gcn_hidden, out_dim),
nn.LayerNorm(out_dim),
nn.GELU(),
nn.Dropout(0.1),
)
self.mamba = _build_mamba(d_model=out_dim, d_state=16,
d_conv=4, expand=2, n_layers=2)
self.norm = nn.LayerNorm(out_dim)
def forward(self, batched_frames: list) -> torch.Tensor:
gcn_out = []
for fb in batched_frames:
x = F.relu(self.bn1(self.conv1(fb.x, fb.edge_index)))
x = self.drop(x)
x = F.relu(self.bn2(self.conv2(x, fb.edge_index)))
x = self.drop(x)
gcn_out.append(global_mean_pool(x, fb.batch)) # (B, gcn_hidden)
x = self.proj(torch.stack(gcn_out, dim=1)) # (B, T, out_dim)
return self.norm(self.mamba(x)) # (B, T, out_dim)
# ββ CrossAttentionFusion βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class CrossAttentionFusion(nn.Module):
"""
Bidirectional cross-attention between VideoMAE patch tokens and landmark tokens.
- LM tokens attend to ViT patches (lm2vit)
- ViT CLS attends to LM tokens (vit2lm)
Output: (cls_out (B, 768), lm_mean (B, 768))
Concatenated upstream β (B, 1536)
"""
def __init__(self, videomae_dim: int = 768, lm_dim: int = 96,
num_heads: int = 8, dropout: float = 0.1):
super().__init__()
self.proj_lm = nn.Linear(lm_dim, videomae_dim)
self.proj_out = nn.Linear(videomae_dim, videomae_dim)
self.cross_lm2vit = nn.MultiheadAttention(
videomae_dim, num_heads, dropout=dropout, batch_first=True
)
self.cross_vit2lm = nn.MultiheadAttention(
videomae_dim, num_heads, dropout=dropout, batch_first=True
)
self.norm1 = nn.LayerNorm(videomae_dim)
self.norm2 = nn.LayerNorm(videomae_dim)
self.drop = nn.Dropout(dropout)
def forward(self, vit_tokens: torch.Tensor,
lm_tokens: torch.Tensor) -> tuple:
# vit_tokens : (B, N_patches, 768)
# lm_tokens : (B, T, 96)
lm_proj = self.proj_lm(lm_tokens) # (B, T, 768)
lm_attended, _ = self.cross_lm2vit(lm_proj, vit_tokens, vit_tokens)
lm_out = self.norm1(lm_proj + self.drop(lm_attended)) # (B, T, 768)
cls = vit_tokens[:, :1, :] # (B, 1, 768)
cls_attended, _ = self.cross_vit2lm(cls, lm_out, lm_out)
cls_out = self.norm2(cls + self.drop(cls_attended)) # (B, 1, 768)
return cls_out.squeeze(1), lm_out.mean(dim=1) # (B,768), (B,768)
# ββ VideoMAELandmarkModel ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class VideoMAELandmarkModel(nn.Module):
"""
Full multimodal model: VideoMAE backbone + GCN landmark encoder +
bidirectional cross-attention fusion + MLP classifier.
forward(video, graphs) β (logits (B, num_classes), feats (B, 256))
Classifier head: 1536 β 512 β 128 β num_classes
(fusion_dim = vit_dim + vit_dim = 768 + 768 = 1536)
"""
def __init__(
self,
num_classes: int = 14,
lm_hidden: int = 48,
lm_out: int = 96,
videomae_name: str = "MCG-NJU/videomae-base-finetuned-kinetics",
dropout: float = 0.4,
):
super().__init__()
from transformers import VideoMAEModel as _VideoMAEModel
self.videomae = _VideoMAEModel.from_pretrained(videomae_name)
self.vit_dim = self.videomae.config.hidden_size # 768
self.lm_encoder = LandmarkGCNEncoder(lm_hidden, lm_out, dropout)
self.fusion = CrossAttentionFusion(self.vit_dim, lm_out, num_heads=8)
fusion_dim = self.vit_dim + self.vit_dim # 1536
self.feat_proj = nn.Linear(fusion_dim, 256)
self.classifier = nn.Sequential(
nn.Linear(fusion_dim, 512),
nn.BatchNorm1d(512), nn.GELU(), nn.Dropout(dropout),
nn.Linear(512, 128),
nn.BatchNorm1d(128), nn.GELU(), nn.Dropout(dropout * 0.5),
nn.Linear(128, num_classes),
)
def forward(self, video: torch.Tensor, graphs: list) -> tuple:
# video : (B, T, C, H, W)
vit_out = self.videomae(pixel_values=video)
vit_tokens = vit_out.last_hidden_state # (B, N, 768)
lm_tokens = self.lm_encoder(graphs) # (B, T, 96)
cls_fused, lm_mean = self.fusion(vit_tokens, lm_tokens)
fused = torch.cat([cls_fused, lm_mean], dim=1) # (B, 1536)
feats = self.feat_proj(fused) # (B, 256)
logits = self.classifier(fused) # (B, num_classes)
return logits, feats
def load_model(model_path: str, device: torch.device) -> VideoMAELandmarkModel:
"""Load VideoMAELandmarkModel from a checkpoint file."""
ckpt = torch.load(model_path, map_location=device, weights_only=False)
cfg = ckpt.get("config", {})
model = VideoMAELandmarkModel(
num_classes=cfg.get("NUM_CLASSES", 14),
lm_hidden=48,
lm_out=96,
videomae_name="MCG-NJU/videomae-base-finetuned-kinetics",
dropout=0.4,
).to(device)
model.load_state_dict(ckpt["model_state_dict"])
model.eval()
epoch = ckpt.get("epoch", "?")
val_f1 = ckpt.get("best_val_f1", float("nan"))
print(f"[model] Loaded β epoch {epoch} | Val F1: {val_f1:.4f}")
return model |