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
| import torch import torch.nn as nn import torch.nn.functional as F
class SymmetricCrossAttention(nn.Module): """对称交叉注意力模块 头部特征和视线特征互相增强 """ def __init__(self, head_dim: int = 256, gaze_dim: int = 256, num_heads: int = 8, dropout: float = 0.1): super().__init__() self.num_heads = num_heads self.head_dim = head_dim self.gaze_dim = gaze_dim self.head_to_gaze_attn = nn.MultiheadAttention( embed_dim=head_dim, num_heads=num_heads, dropout=dropout, batch_first=True ) self.gaze_to_head_attn = nn.MultiheadAttention( embed_dim=gaze_dim, num_heads=num_heads, dropout=dropout, batch_first=True ) self.norm1 = nn.LayerNorm(head_dim) self.norm2 = nn.LayerNorm(gaze_dim) self.ffn_head = nn.Sequential( nn.Linear(head_dim, head_dim * 4), nn.GELU(), nn.Dropout(dropout), nn.Linear(head_dim * 4, head_dim), ) self.ffn_gaze = nn.Sequential( nn.Linear(gaze_dim, gaze_dim * 4), nn.GELU(), nn.Dropout(dropout), nn.Linear(gaze_dim * 4, gaze_dim), ) def forward(self, head_features: torch.Tensor, gaze_features: torch.Tensor) -> tuple: """ Args: head_features: (B, N, head_dim) 头部特征 gaze_features: (B, N, gaze_dim) 视线特征 Returns: (enhanced_head, enhanced_gaze) """ gaze_enhanced, _ = self.head_to_gaze_attn( query=gaze_features, key=head_features, value=head_features ) gaze_features = self.norm2(gaze_features + gaze_enhanced) gaze_features = gaze_features + self.ffn_gaze(gaze_features) head_enhanced, _ = self.gaze_to_head_attn( query=head_features, key=gaze_features, value=gaze_features ) head_features = self.norm1(head_features + head_enhanced) head_features = head_features + self.ffn_head(head_features) return head_features, gaze_features
class GazeSymCAT(nn.Module): """GazeSymCAT 完整模型""" def __init__(self, backbone: str = 'resnet18', pretrained: bool = True, feature_dim: int = 256, num_sa_layers: int = 2, num_ca_layers: int = 2): super().__init__() if backbone == 'resnet18': self.backbone = torch.hub.load( 'pytorch/vision:v0.10.0', 'resnet18', pretrained=pretrained ) backbone_dim = 512 elif backbone == 'efficientnet_b0': self.backbone = torch.hub.load( 'NVIDIA/DeepLearningExamples:torchhub', 'nvidia_efficientnet_b0', pretrained=pretrained ) backbone_dim = 1280 self.head_proj = nn.Linear(backbone_dim, feature_dim) self.gaze_proj = nn.Linear(backbone_dim, feature_dim) self.self_attn_layers = nn.ModuleList([ nn.TransformerEncoderLayer( d_model=feature_dim, nhead=8, dim_feedforward=feature_dim * 4, dropout=0.1, batch_first=True ) for _ in range(num_sa_layers) ]) self.cross_attn_layers = nn.ModuleList([ SymmetricCrossAttention( head_dim=feature_dim, gaze_dim=feature_dim ) for _ in range(num_ca_layers) ]) self.fusion = nn.Sequential( nn.Linear(feature_dim * 2, feature_dim), nn.GELU(), nn.Dropout(0.1), nn.Linear(feature_dim, 2) ) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: (B, C, H, W) 输入图像(人脸区域) Returns: (B, 2) 视线方向 (pitch, yaw) """ B = x.shape[0] features = self.backbone(x) head_features = self.head_proj(features).unsqueeze(1) gaze_features = self.gaze_proj(features).unsqueeze(1) for sa_layer in self.self_attn_layers: head_features = sa_layer(head_features) gaze_features = sa_layer(gaze_features) for ca_layer in self.cross_attn_layers: head_features, gaze_features = ca_layer(head_features, gaze_features) combined = torch.cat([head_features, gaze_features], dim=-1).squeeze(1) gaze = self.fusion(combined) return gaze
def angular_error(pred: torch.Tensor, gt: torch.Tensor) -> torch.Tensor: """计算角度误差 Args: pred: (B, 2) 预测的 (pitch, yaw) gt: (B, 2) 真实的 (pitch, yaw) Returns: (B,) 角度误差(度) """ pred_vec = torch.stack([ torch.cos(pred[:, 0]) * torch.sin(pred[:, 1]), torch.sin(pred[:, 0]), torch.cos(pred[:, 0]) * torch.cos(pred[:, 1]) ], dim=-1) gt_vec = torch.stack([ torch.cos(gt[:, 0]) * torch.sin(gt[:, 1]), torch.sin(gt[:, 0]), torch.cos(gt[:, 0]) * torch.cos(gt[:, 1]) ], dim=-1) cos_angle = torch.sum(pred_vec * gt_vec, dim=-1) / ( torch.norm(pred_vec, dim=-1) * torch.norm(gt_vec, dim=-1) + 1e-8 ) cos_angle = torch.clamp(cos_angle, -1, 1) return torch.acos(cos_angle) * 180 / torch.pi
|