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
| import torch import torch.nn as nn import numpy as np from typing import List, Dict
class SeMA(nn.Module): """ Sequential Modality Aggregator (SeMA) 顺序模态聚合器: 1. 按需选择模态编码 2. 只运行选中的编码器和融合分支 3. 固定大小状态更新 4. 每次获取后即可预测 """ def __init__(self, modalities: List[str], d_model: int = 256, n_classes: int = 5): super().__init__() self.modalities = modalities self.encoders = nn.ModuleDict({ mod: self._build_encoder(mod, d_model) for mod in modalities }) self.fusion_state = nn.GRUCell(d_model, d_model) self.classifier = nn.Sequential( nn.Linear(d_model, d_model // 2), nn.GELU(), nn.Linear(d_model // 2, n_classes) ) def _build_encoder(self, mod: str, d_model: int) -> nn.Module: if mod == "camera": return nn.Sequential( nn.Conv2d(3, 32, 3, 2, 1), nn.GELU(), nn.Conv2d(32, 64, 3, 2, 1), nn.GELU(), nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(64, d_model) ) elif mod == "radar": return nn.Sequential( nn.Linear(50, 128), nn.GELU(), nn.Linear(128, d_model) ) elif mod == "rppg": return nn.Sequential( nn.Linear(10, 64), nn.GELU(), nn.Linear(64, d_model) ) elif mod == "steering": return nn.Sequential( nn.Linear(5, 32), nn.GELU(), nn.Linear(32, d_model) ) return nn.Linear(10, d_model) def forward(self, inputs: Dict[str, torch.Tensor], acquisition_order: List[str]) -> List[torch.Tensor]: """ Args: inputs: 各模态输入数据 acquisition_order: 模态获取顺序 Returns: predictions: 每次获取后的预测列表 """ state = torch.zeros(1, 256, device=next(self.parameters()).device) predictions = [] for mod in acquisition_order: if mod not in inputs or inputs[mod] is None: continue x = inputs[mod] if mod == "camera": feat = self.encoders[mod](x) else: feat = self.encoders[mod](x) state = self.fusion_state(feat.unsqueeze(0), state) pred = self.classifier(state) predictions.append(pred) return predictions
class ARC(nn.Module): """ Adaptive Runtime Controller (ARC) 自适应运行时控制器: 1. 基于当前状态选择下一个模态 2. 或决定停止(已有证据足够) 3. 结合边际效用先验 + 残差Q学习 """ def __init__(self, modalities: List[str], d_model: int = 256): super().__init__() self.modalities = modalities self.marginal_prior = nn.Parameter(torch.ones(len(modalities))) self.q_net = nn.Sequential( nn.Linear(d_model + len(modalities), 128), nn.GELU(), nn.Linear(128, len(modalities) + 1) ) def forward(self, state: torch.Tensor, acquired: List[str]) -> Dict: """ 决定下一个模态或停止 Returns: action: {"type": "acquire"/"stop", "modality": str} """ acquired_mask = torch.zeros(len(self.modalities)) for i, mod in enumerate(self.modalities): if mod in acquired: acquired_mask[i] = 1 prior = self.marginal_prior * (1 - acquired_mask) q_input = torch.cat([state.squeeze(0), acquired_mask]) q_values = self.q_net(q_input) combined = prior + q_values[:-1] stop_q = q_values[-1] best_mod_idx = combined.argmax().item() best_mod_q = combined[best_mod_idx].item() if stop_q > best_mod_q: return {"type": "stop", "reason": "evidence_sufficient"} else: return { "type": "acquire", "modality": self.modalities[best_mod_idx], "expected_gain": best_mod_q - stop_q }
class SemARC(nn.Module): """完整的SemARC系统""" def __init__(self, modalities: List[str]): super().__init__() self.sema = SeMA(modalities) self.arc = ARC(modalities) self.modalities = modalities def forward(self, inputs: Dict[str, torch.Tensor]) -> Dict: """ 自适应推理流程 1. ARC选择第一个模态 2. SeMA编码+融合 3. ARC选择第二个或停止 4. 重复直到停止 """ acquired = [] state = torch.zeros(1, 256) final_pred = None total_gflops = 0 order = ["steering", "rppg", "camera", "radar"] for mod in order: if mod not in inputs: continue acquired.append(mod) if mod == "steering": total_gflops += 0.01 elif mod == "rppg": total_gflops += 0.05 elif mod == "camera": total_gflops += 2.5 elif mod == "radar": total_gflops += 1.0 decision = self.arc(state, acquired) if decision["type"] == "stop": break return { "acquired_modalities": acquired, "total_gflops": total_gflops, "stopped_early": len(acquired) < len(self.modalities), "savings_vs_full": 1 - total_gflops / 3.56 }
if __name__ == "__main__": system = SemARC(["camera", "radar", "rppg", "steering"]) inputs_normal = { "steering": torch.randn(1, 5), "rppg": torch.randn(1, 10), "camera": torch.randn(1, 3, 224, 224), "radar": torch.randn(1, 50), } result = system(inputs_normal) print("正常驾驶:") print(f" 获取模态: {result['acquired_modalities']}") print(f" GFLOPs: {result['total_gflops']:.2f}") print(f" 节省: {result['savings_vs_full']*100:.1f}%") print(f" 提前停止: {result['stopped_early']}")
|