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
| import torch import torch.nn as nn import torch.nn.functional as F import numpy as np
class LISA(nn.Module): """ LISA: Language-guided Interference-aware Spatial-Frequency Attention 核心组件: 1. FAM Fusion - 频域注意力融合 2. SDM - 语义解耦模块(CLIP引导) """ def __init__(self, config: dict): super().__init__() self.backbone = ResNet18Backbone() self.fam_fusion = FAMFusion( spatial_dim=512, frequency_dim=512 ) self.spatial_gate = SpatialSaliencyGating(512) self.sdm = SemanticDisentanglementModule( feature_dim=512, clip_model='ViT-B/32' ) self.gaze_regressor = nn.Sequential( nn.Linear(512, 256), nn.ReLU(inplace=True), nn.Dropout(0.3), nn.Linear(256, 2) ) def forward(self, image: torch.Tensor) -> dict: """ Args: image: (B, 3, H, W) RGB图像 Returns: gaze: (B, 2) 视线角度 [pitch, yaw] features: 解耦后的特征 """ spatial_feat = self.backbone(image) fused_feat = self.fam_fusion(spatial_feat, image) gated_feat = self.spatial_gate(fused_feat) disentangled_feat, disentangle_loss = self.sdm(gated_feat) gaze = self.gaze_regressor(disentangled_feat) return { 'gaze': gaze, 'features': disentangled_feat, 'disentangle_loss': disentangle_loss }
class FAMFusion(nn.Module): """ Frequency-Attention Modulated Fusion 将频域稳定特征注入空间特征 """ def __init__(self, spatial_dim: int, frequency_dim: int): super().__init__() self.spectral_injection = SpectralInjectionBlock(spatial_dim) self.fusion = nn.Sequential( nn.Linear(spatial_dim + frequency_dim, spatial_dim), nn.ReLU(inplace=True) ) def forward(self, spatial_feat: torch.Tensor, image: torch.Tensor) -> torch.Tensor: """ Args: spatial_feat: (B, C, H, W) 空间特征 image: (B, 3, H, W) 原始图像 Returns: fused: (B, C, H, W) 融合特征 """ freq_feat = self._extract_frequency_features(image) injected_feat = self.spectral_injection(spatial_feat, freq_feat) return injected_feat def _extract_frequency_features(self, image: torch.Tensor) -> torch.Tensor: """提取频域特征""" B, C, H, W = image.shape freq = torch.fft.fft2(image, dim=(-2, -1)) amp = torch.abs(freq) phase = torch.angle(freq) log_amp = torch.log(amp + 1e-8) low_freq = self._extract_low_frequency(log_amp, ratio=0.1) return low_freq def _extract_low_frequency(self, amp: torch.Tensor, ratio: float) -> torch.Tensor: """提取低频分量""" B, C, H, W = amp.shape amp_shift = torch.fft.fftshift(amp, dim=(-2, -1)) mask = torch.zeros_like(amp_shift) center_h, center_w = H // 2, W // 2 radius_h, radius_w = int(H * ratio), int(W * ratio) mask[:, :, center_h-radius_h:center_h+radius_h, center_w-radius_w:center_w+radius_w] = 1.0 low_freq = amp_shift * mask return low_freq
class SpectralInjectionBlock(nn.Module): """频谱注入块""" def __init__(self, channels: int): super().__init__() self.channel_attention = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Conv2d(channels, channels // 16, 1), nn.ReLU(inplace=True), nn.Conv2d(channels // 16, channels, 1), nn.Sigmoid() ) def forward(self, spatial_feat: torch.Tensor, freq_feat: torch.Tensor) -> torch.Tensor: """ 将频域特征注入空间特征 """ freq_up = F.interpolate(freq_feat, size=spatial_feat.shape[-2:], mode='bilinear', align_corners=False) attention = self.channel_attention(spatial_feat) injected = spatial_feat + attention * freq_up return injected
class SpatialSaliencyGating(nn.Module): """空间显著性门控""" def __init__(self, channels: int): super().__init__() self.gate = nn.Sequential( nn.Conv2d(channels, 1, 1), nn.Sigmoid() ) def forward(self, feat: torch.Tensor) -> torch.Tensor: """ 突出眼部区域 """ saliency_map = self.gate(feat) return feat * saliency_map
class SemanticDisentanglementModule(nn.Module): """ Semantic Disentanglement Module 使用CLIP分离视线特征与外观干扰 """ DISTRACTOR_TEMPLATES = [ "a driver wearing sunglasses", "a driver wearing a mask", "a driver with glasses", "a driver with hat" ] def __init__(self, feature_dim: int, clip_model: str = 'ViT-B/32'): super().__init__() self.clip_encoder = self._load_clip(clip_model) self.text_embeddings = self._encode_distractors() self.projector = nn.Linear(feature_dim, 512) def forward(self, features: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ Args: features: (B, D) 输入特征 Returns: disentangled: 解耦特征 loss: 解耦损失 """ projected = self.projector(features) similarity = F.cosine_similarity( projected.unsqueeze(1), self.text_embeddings.unsqueeze(0), dim=-1 ) push_loss = similarity.mean() ortho_loss = self._orthogonal_loss(projected) total_loss = push_loss + 0.1 * ortho_loss return features, total_loss def _load_clip(self, model_name: str): """加载CLIP模型""" import clip model, _ = clip.load(model_name, device='cuda') for param in model.parameters(): param.requires_grad = False return model def _encode_distractors(self) -> torch.Tensor: """编码干扰文本""" import clip text_tokens = clip.tokenize(self.DISTRACTOR_TEMPLATES).cuda() with torch.no_grad(): text_features = self.clip_encoder.encode_text(text_tokens) return text_features.float() def _orthogonal_loss(self, features: torch.Tensor) -> torch.Tensor: """正交约束损失""" ortho = torch.mm(features, self.text_embeddings.T) loss = (ortho ** 2).mean() return loss
if __name__ == "__main__": model = LISA({}) model.eval() image = torch.randn(2, 3, 224, 224) with torch.no_grad(): result = model(image) print(f"视线预测: {result['gaze']}") print(f"解耦损失: {result['disentangle_loss']:.4f}")
|