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 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
| import torch import torch.nn as nn import torch.nn.functional as F
class ModalityEncoder(nn.Module): """ 模态特定编码器 每种传感器数据用独立编码器提取特征 """ def __init__(self, modality: str, embed_dim: int = 256): super().__init__() self.modality = modality if modality == 'vision': self.encoder = nn.Sequential( nn.Conv2d(3, 32, 3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(64, 128, 3, stride=2, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(128, embed_dim) ) elif modality == 'radar': self.encoder = nn.Sequential( nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.Conv2d(16, 32, 3, stride=2, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(32, embed_dim) ) elif modality == 'telemetry': self.encoder = nn.Sequential( nn.Linear(10, 64), nn.ReLU(), nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, embed_dim) ) def forward(self, x: torch.Tensor) -> torch.Tensor: return self.encoder(x)
class CrossModalFusion(nn.Module): """ 跨模态表示融合 将多模态特征融合为统一的紧凑表示 """ def __init__(self, embed_dim: int = 256, num_modalities: int = 3): super().__init__() self.num_modalities = num_modalities self.cross_attn = nn.MultiheadAttention( embed_dim, num_heads=8, batch_first=True ) self.fusion = nn.Sequential( nn.Linear(embed_dim * num_modalities, embed_dim * 2), nn.GELU(), nn.Linear(embed_dim * 2, embed_dim) ) def forward(self, modality_feats: list) -> torch.Tensor: """ Args: modality_feats: list of (B, embed_dim) tensors Returns: fused: (B, embed_dim) 融合表示 """ seq = torch.stack(modality_feats, dim=1) attn_out, _ = self.cross_attn(seq, seq, seq) concat = attn_out.flatten(1) fused = self.fusion(concat) return fused
class LearnedCompression(nn.Module): """ 学习型压缩模块 将融合表示压缩为固定大小的紧凑向量 用于边缘→云端传输 目标: 最小化传输数据量, 最大化下游任务精度 """ def __init__(self, embed_dim: int = 256, compressed_dim: int = 64): super().__init__() self.compressor = nn.Sequential( nn.Linear(embed_dim, 128), nn.GELU(), nn.Linear(128, compressed_dim) ) self.decompressor = nn.Sequential( nn.Linear(compressed_dim, 128), nn.GELU(), nn.Linear(128, embed_dim) ) def compress(self, x: torch.Tensor) -> torch.Tensor: """边缘侧: 压缩""" return self.compressor(x) def decompress(self, x: torch.Tensor) -> torch.Tensor: """云端侧: 解压""" return self.decompressor(x) def forward(self, x: torch.Tensor) -> torch.Tensor: """端到端: 压缩+解压""" return self.decompress(self.compress(x))
class EMMIEdgeSystem(nn.Module): """ EMMI: 完整的边缘多模态系统 边缘侧: 多模态编码 → 融合 → 压缩 → 传输 云端侧: 解压 → MLLM推理 → 结果 论文Section 3: System Architecture """ def __init__(self, modalities: list = ['vision', 'radar', 'telemetry'], embed_dim: int = 256, compressed_dim: int = 64): super().__init__() self.modalities = modalities self.encoders = nn.ModuleDict({ m: ModalityEncoder(m, embed_dim) for m in modalities }) self.fusion = CrossModalFusion(embed_dim, len(modalities)) self.compression = LearnedCompression(embed_dim, compressed_dim) self.task_head = nn.Sequential( nn.Linear(embed_dim, 128), nn.GELU(), nn.Linear(128, 5) ) def edge_forward(self, inputs: dict) -> torch.Tensor: """ 边缘侧前向传播(输出压缩表示) """ feats = [] for mod in self.modalities: if mod in inputs: feats.append(self.encoders[mod](inputs[mod])) fused = self.fusion(feats) compressed = self.compression.compress(fused) return compressed def cloud_forward(self, compressed: torch.Tensor) -> torch.Tensor: """ 云端侧前向传播(接收压缩表示,执行推理) """ decompressed = self.compression.decompress(compressed) logits = self.task_head(decompressed) return logits def forward(self, inputs: dict) -> dict: """端到端""" compressed = self.edge_forward(inputs) logits = self.cloud_forward(compressed) original_size = sum( inputs[m].numel() for m in self.modalities if m in inputs ) compressed_size = compressed.numel() compression_ratio = original_size / compressed_size return { 'logits': logits, 'compressed': compressed, 'compression_ratio': compression_ratio }
if __name__ == "__main__": import numpy as np import time from sklearn.metrics import accuracy_score BATCH_SIZE = 16 MODALITIES = ['vision', 'radar', 'telemetry'] model = EMMIEdgeSystem( modalities=MODALITIES, embed_dim=256, compressed_dim=64 ) total_params = sum(p.numel() for p in model.parameters()) print(f"EMMI参数量: {total_params:,}") np.random.seed(42) def generate_multimodal_input(state: str, batch=1): """生成多模态输入""" if state == 'normal': vision = torch.rand(batch, 3, 224, 224) * 0.5 + 0.3 radar = torch.rand(batch, 1, 64, 64) * 0.3 telemetry = torch.rand(batch, 10) * 0.5 elif state == 'fatigue': vision = torch.rand(batch, 3, 224, 224) * 0.3 + 0.2 radar = torch.rand(batch, 1, 64, 64) * 0.2 telemetry = torch.rand(batch, 10) * 0.3 + torch.tensor([ 0.8, 0.2, 0.1, 0.5, 0.3, 0.7, 0.4, 0.2, 0.6, 0.3 ]) elif state == 'phone': vision = torch.rand(batch, 3, 224, 224) * 0.7 + 0.3 radar = torch.rand(batch, 1, 64, 64) * 0.5 telemetry = torch.rand(batch, 10) * 0.8 + torch.tensor([ 0.5, 0.9, 0.3, 0.2, 0.5, 0.8, 0.1, 0.3, 0.4, 0.2 ]) return {'vision': vision, 'radar': radar, 'telemetry': telemetry} print("\n--- 生成多模态数据 ---") states = ['normal', 'fatigue', 'phone', 'normal', 'fatigue'] all_inputs = [] all_labels = [] for i, state in enumerate(states): inputs = generate_multimodal_input(state, batch=4) all_inputs.append(inputs) all_labels.extend([i] * 4) batch_inputs = { mod: torch.cat([inp[mod] for inp in all_inputs]) for mod in MODALITIES } labels = torch.tensor(all_labels) print(f" Vision: {batch_inputs['vision'].shape}") print(f" Radar: {batch_inputs['radar'].shape}") print(f" Telemetry: {batch_inputs['telemetry'].shape}") print("\n--- EMMI前向传播 ---") model.eval() with torch.no_grad(): out = model(batch_inputs) print(f" Logits: {out['logits'].shape}") print(f" Compressed: {out['compressed'].shape}") print(f" 压缩比: {out['compression_ratio']:.1f}×") print(f" 原始数据: {sum(batch_inputs[m].numel() for m in MODALITIES):,} bytes") print(f" 压缩后: {out['compressed'].numel():,} bytes") print("\n--- 训练流程 ---") criterion = nn.CrossEntropyLoss() optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4) model.train() for epoch in range(5): optimizer.zero_grad() out = model(batch_inputs) loss = criterion(out['logits'], labels) loss.backward() optimizer.step() acc = accuracy_score(labels.numpy(), torch.argmax(out['logits'], dim=1).detach().numpy()) print(f"Epoch {epoch+1}: Loss={loss.item():.4f}, Acc={acc:.2%}, " f"Compression={out['compression_ratio']:.1f}×") print("\n--- 通信效率分析 ---") original_bytes = sum(batch_inputs[m].numel() * 4 for m in MODALITIES) compressed_bytes = out['compressed'].numel() * 4 print(f" 原始传输: {original_bytes/1024:.1f} KB/sample") print(f" EMMI传输: {compressed_bytes/1024:.1f} KB/sample") print(f" 节省: {(1-compressed_bytes/original_bytes)*100:.1f}%") bandwidth_mbps = 10 original_latency = (original_bytes * 8) / (bandwidth_mbps * 1e6) * 1000 emmi_latency = (compressed_bytes * 8) / (bandwidth_mbps * 1e6) * 1000 print(f"\n 原始传输延迟: {original_latency:.1f}ms (@{bandwidth_mbps}Mbps)") print(f" EMMI传输延迟: {emmi_latency:.1f}ms") print(f" 延迟降低: {(1-emmi_latency/original_latency)*100:.1f}%")
|