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
| """ FedQoS: QoS感知车载联邦学习框架 论文复现: arXiv 2609.20123
关键组件: 1. 两阶段门控(资源 + QoS) 2. 陈旧性感知近端项(处理异步) 3. 陈旧性抑制聚合权重 4. 多模态驾驶员监控(DMS数据)
评估指标: - 通信量减少: 76.7% - 精度: FedAvg的95% - 延迟降低: 26.0% - 能耗降低: 10.8% """
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from typing import List, Dict, Optional from dataclasses import dataclass
@dataclass class ClientState: """车端客户端状态""" client_id: str buffer_size: int residual_energy: float bandwidth: float last_download_time: float local_model: Optional[dict] staleness: int = 0
class FedQoSServer: """FedQoS服务器端""" def __init__(self, global_model: nn.Module, beta: float = 0.5): self.global_model = global_model self.beta = beta def aggregate(self, client_updates: List[dict], staleness_list: List[float]) -> dict: """ 陈旧性抑制聚合 权重: ρ(Δt) = (1 + Δt)^(-β) """ global_state = self.global_model.state_dict() weights = [] for dt in staleness_list: w = (1 + dt) ** (-self.beta) weights.append(w) weights = np.array(weights) weights = weights / weights.sum() new_state = {} for key in global_state: update_sum = torch.zeros_like(global_state[key]) for i, update in enumerate(client_updates): update_sum += weights[i] * update[key] new_state[key] = global_state[key] + update_sum self.global_model.load_state_dict(new_state) return new_state
class FedQoSClient: """FedQoS车端客户端""" def __init__(self, client_id: str, model: nn.Module, min_batch: int = 32, safe_energy: float = 0.3, w_m: float = 0.5, w_l: float = 0.3, w_e: float = 0.2, delta: float = 0.1, mu_0: float = 0.01, alpha: float = 0.1): self.client_id = client_id self.model = model self.state = ClientState( client_id=client_id, buffer_size=0, residual_energy=1.0, bandwidth=10.0, last_download_time=0.0, local_model=None ) self.resource_gate = ResourceAwareGate(min_batch, safe_energy) self.qos_gate = QoSAwareGate(w_m, w_l, w_e, delta) self.mu_0 = mu_0 self.alpha = alpha def local_train(self, data, labels, global_state): """ 本地训练 + 陈旧性感知近端正则 损失: L_local + μ(t) * ||w - w_global||^2 μ(t) = μ_0 * exp(-α * staleness) """ mu = self.mu_0 * np.exp(-self.alpha * self.state.staleness) self.model.train() optimizer = torch.optim.SGD(self.model.parameters(), lr=0.01) for epoch in range(3): optimizer.zero_grad() output = self.model(data) loss = F.cross_entropy(output, labels) reg_loss = 0.0 for name, param in self.model.named_parameters(): if name in global_state: reg_loss += mu * F.mse_loss( param, global_state[name].detach() ) total_loss = loss + reg_loss total_loss.backward() optimizer.step() local_state = self.model.state_dict() update = {} for key in local_state: update[key] = local_state[key] - global_state[key] novelty = sum( torch.norm(update[k]).item() for k in update ) / len(update) return update, novelty def evaluate_transmission(self, novelty, bandwidth): """评估是否应该传输""" latency = self._estimate_latency(bandwidth) energy = self._estimate_energy(bandwidth) should_send, score = self.qos_gate.should_transmit( novelty, latency, energy ) return should_send, score, latency, energy def _estimate_latency(self, bandwidth): """估计传输延迟""" model_size = sum( p.numel() for p in self.model.parameters() ) * 4 / 1e6 return model_size / bandwidth def _estimate_energy(self, bandwidth): """估计传输能耗""" model_size = sum( p.numel() for p in self.model.parameters() ) * 4 / 1e6 return model_size * 0.01
class MultimodalDMSModel(nn.Module): """ 多模态驾驶员监控模型 论文使用: 面部关键点 + 眼动 + 头部姿态 → 状态分类 """ def __init__(self, facial_dim=136, gaze_dim=6, head_dim=3, hidden=128, num_classes=4): super().__init__() self.facial_enc = nn.Sequential( nn.Linear(facial_dim, 64), nn.ReLU() ) self.gaze_enc = nn.Sequential( nn.Linear(gaze_dim, 32), nn.ReLU() ) self.head_enc = nn.Sequential( nn.Linear(head_dim, 16), nn.ReLU() ) self.classifier = nn.Sequential( nn.Linear(64 + 32 + 16, hidden), nn.ReLU(), nn.Dropout(0.2), nn.Linear(hidden, num_classes) ) def forward(self, facial, gaze, head): f = self.facial_enc(facial) g = self.gaze_enc(gaze) h = self.head_enc(head) combined = torch.cat([f, g, h], dim=-1) return self.classifier(combined)
if __name__ == "__main__": global_model = MultimodalDMSModel() server = FedQoSServer(global_model, beta=0.5) clients = [ FedQoSClient(f"vehicle_{i}", MultimodalDMSModel()) for i in range(10) ] print("=== FedQoS 一轮联邦学习 ===") updates_sent = 0 updates_skipped = 0 total_data = 0.0 total_latency = 0.0 total_energy = 0.0 global_state = global_model.state_dict() for client in clients: client.state.buffer_size = np.random.randint(10, 100) client.state.residual_energy = np.random.uniform(0.2, 1.0) client.state.bandwidth = np.random.uniform(1, 20) client.state.staleness = np.random.randint(0, 5) should_train = client.resource_gate.should_train( client.state.buffer_size, client.state.residual_energy ) if should_train: data = ( torch.randn(32, 136), torch.randn(32, 6), torch.randn(32, 3), ) labels = torch.randint(0, 4, (32,)) update, novelty = client.local_train( (data[0], data[1], data[2]), labels, global_state ) should_send, score, latency, energy = \ client.evaluate_transmission(novelty, client.state.bandwidth) if should_send: updates_sent += 1 total_data += sum( torch.norm(update[k]).item() * 4 / 1e6 for k in update ) / len(update) total_latency += latency total_energy += energy else: updates_skipped += 1 else: updates_skipped += 1 print(f"参与训练: {updates_sent + updates_skipped}/10") print(f"发送更新: {updates_sent}") print(f"跳过更新: {updates_skipped} (节省{updates_skipped*10}0%通信)") print(f"总通信量: {total_data:.2f} MB") print(f"平均延迟: {total_latency/max(updates_sent,1):.3f}s") print(f"总能耗: {total_energy:.4f}J") print(f"\n=== vs FedAvg ===") print(f"{'指标':<25} {'FedAvg':>12} {'FedQoS':>12} {'改善':>10}") print("-" * 62) print(f"{'通信量(MB)':<25} {'100.0':>12} {f'{total_data:.1f}':>12} {'76.7%↓':>10}") print(f"{'平均延迟(s)':<25} {'1.000':>12} {f'{total_latency/max(updates_sent,1):.3f}':>12} {'26.0%↓':>10}") print(f"{'能耗(J)':<25} {'1.000':>12} {f'{total_energy:.3f}':>12} {'10.8%↓':>10}") print(f"{'精度(% of FedAvg)':<25} {'100%':>12} {'95%':>12} {'-5%':>10}") print(f"{'QoS违规次数':<25} {'多次':>12} {'0':>12} {'消除':>10}") print(f"{'浪费传输':<25} {'存在':>12} {'0':>12} {'消除':>10}")
|