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
| import torch import torch.nn as nn from typing import Tuple, Optional
class CCGF(nn.Module): """ Causal Context-Gated Forecaster (CCGF) 因果注视预测器: - 输入:60帧历史注视+头部姿态 + DINOv3场景特征 - 输出:当前时刻注视方向预测 - 关键:可靠性门控动态融合历史和场景信息 论文:arXiv:2609.12374 """ def __init__( self, gaze_dim: int = 2, head_dim: int = 6, scene_dim: int = 768, hidden_dim: int = 256, history_frames: int = 60, ): super().__init__() self.history_frames = history_frames input_dim = gaze_dim + head_dim self.temporal_encoder = nn.LSTM( input_size=input_dim, hidden_size=hidden_dim, num_layers=2, batch_first=True, dropout=0.1, ) self.scene_projector = nn.Sequential( nn.Linear(scene_dim, hidden_dim), nn.GELU(), nn.Linear(hidden_dim, hidden_dim), ) self.history_gate = nn.Sequential( nn.Linear(hidden_dim, hidden_dim // 4), nn.GELU(), nn.Linear(hidden_dim // 4, 1), nn.Sigmoid(), ) self.scene_gate = nn.Sequential( nn.Linear(hidden_dim, hidden_dim // 4), nn.GELU(), nn.Linear(hidden_dim // 4, 1), nn.Sigmoid(), ) self.fusion = nn.Sequential( nn.Linear(hidden_dim * 2, hidden_dim), nn.GELU(), nn.Dropout(0.2), nn.Linear(hidden_dim, hidden_dim // 2), nn.GELU(), nn.Linear(hidden_dim // 2, gaze_dim), ) def forward( self, gaze_history: torch.Tensor, head_history: torch.Tensor, scene_features: torch.Tensor, dropout_progress: float = 0.0, ) -> torch.Tensor: """ 因果注视预测 Args: gaze_history: dropout前60帧注视轨迹 head_history: 同期头部姿态 scene_features: DINOv3场景特征 - Live: 持续更新(含dropout期间) - Frozen: 冻结最后pre-dropout帧 dropout_progress: 丢失进度(控制门控权重) Returns: predicted_gaze: (B, 2) 预测注视坐标 Example: >>> model = CCGF() >>> gaze = torch.randn(4, 60, 2) # 60帧历史 >>> head = torch.randn(4, 60, 6) >>> scene = torch.randn(4, 768) >>> pred = model(gaze, head, scene, dropout_progress=0.3) >>> print(f"预测注视: {pred.shape}") # (4, 2) """ combined_input = torch.cat([gaze_history, head_history], dim=-1) temporal_out, _ = self.temporal_encoder(combined_input) temporal_feat = temporal_out[:, -1, :] scene_feat = self.scene_projector(scene_features) history_weight = self.history_gate(temporal_feat) * (1 - 0.5 * dropout_progress) scene_weight = self.scene_gate(scene_feat) * (0.5 + 0.5 * dropout_progress) weighted_history = temporal_feat * history_weight weighted_scene = scene_feat * scene_weight fused = torch.cat([weighted_history, weighted_scene], dim=-1) predicted_gaze = self.fusion(fused) return predicted_gaze
class GazeDropoutSimulator: """ 模拟注视追踪丢失场景,用于测试CCGF """ def __init__( self, fps: int = 30, history_frames: int = 60, max_dropout_frames: int = 90, ): self.fps = fps self.history_frames = history_frames self.max_dropout_frames = max_dropout_frames def simulate_dropout( self, full_gaze: torch.Tensor, full_head: torch.Tensor, dropout_start: int, dropout_duration: int, ) -> dict: """ 模拟一次追踪丢失事件 Returns: event: { 'history_gaze': (60, 2), 'history_head': (60, 6), 'dropout_gaze': (duration, 2), # ground truth 'dropout_duration': int, } """ start = max(0, dropout_start - self.history_frames) history_gaze = full_gaze[start:dropout_start] history_head = full_head[start:dropout_start] end = min(len(full_gaze), dropout_start + dropout_duration) dropout_gaze = full_gaze[dropout_start:end] return { 'history_gaze': history_gaze[-self.history_frames:], 'history_head': history_head[-self.history_frames:], 'dropout_gaze': dropout_gaze, 'dropout_duration': dropout_duration, }
if __name__ == "__main__": model = CCGF() B = 4 gaze_hist = torch.randn(B, 60, 2) head_hist = torch.randn(B, 60, 6) scene_feat = torch.randn(B, 768) for progress in [0.0, 0.3, 0.6, 0.9]: pred = model(gaze_hist, head_hist, scene_feat, progress) print(f"丢失进度 {progress:.1f}: 预测注视 = {pred[0].tolist()}") sim = GazeDropoutSimulator() full_gaze = torch.cumsum(torch.randn(300, 2) * 0.5, dim=0) full_head = torch.cumsum(torch.randn(300, 6) * 0.3, dim=0) event = sim.simulate_dropout(full_gaze, full_head, dropout_start=100, dropout_duration=45) predictions = [] for t in range(event['dropout_duration']): progress = t / sim.max_dropout_frames pred = model( event['history_gaze'].unsqueeze(0), event['history_head'].unsqueeze(0), scene_feat[:1], progress, ) predictions.append(pred.squeeze(0)) predictions = torch.stack(predictions) gt = event['dropout_gaze'] errors = torch.norm(predictions - gt, dim=-1) print(f"\n模拟丢失事件 (45帧/1.5s):") print(f" 平均误差: {errors.mean().item():.1f} px") print(f" 最大误差: {errors.max().item():.1f} px") print(f" 模型参数: {sum(p.numel() for p in model.parameters()) / 1e6:.1f}M")
|