联邦学习生产部署实践
将联邦学习从研究原型推进到生产环境,需要解决服务编排、监控、故障恢复和模型治理等问题。
系统架构
┌─────────────────────────────────────────┐
│ 管理控制台 │
│ (任务管理 / 监控 / 审计 / 权限) │
├─────────────────────────────────────────┤
│ 聚合服务 │
│ (FedAvg / 安全聚合 / DP / 检查点) │
├──────────┬──────────┬──────────────────┤
│ 参与方A │ 参与方B │ 参与方C │
│ 训练服务 │ 训练服务 │ 训练服务 │
│ 数据管道 │ 数据管道 │ 数据管道 │
└──────────┴──────────┴──────────────────┘部署架构
python
class FLProductionSystem:
"""联邦学习生产系统"""
def __init__(self, config):
self.aggregator = AggregationService(config)
self.clients = []
self.monitor = MonitoringService()
self.checkpoint = CheckpointService()
def run_training(self, num_rounds=100):
for round_num in range(num_rounds):
try:
# 1. 广播全局模型
self.aggregator.broadcast()
# 2. 收集客户端更新
updates = self.collect_updates(timeout=300)
# 3. 验证更新质量
valid_updates = self.validate_updates(updates)
# 4. 安全聚合
new_model = self.aggregator.aggregate(valid_updates)
# 5. 评估模型
metrics = self.evaluate(new_model)
self.monitor.log(round_num, metrics)
# 6. 检查点
if round_num % 10 == 0:
self.checkpoint.save(new_model, round_num)
# 7. 早停
if self.should_stop(metrics):
break
except Exception as e:
self.monitor.alert(f"Round {round_num} failed: {e}")
self.recover(round_num)监控指标
| 类别 | 指标 | 目标 |
|---|---|---|
| 训练 | Loss/Accuracy | 持续下降 |
| 通信 | 每轮延迟 | < 5分钟 |
| 参与 | 客户端完成率 | > 80% |
| 数据 | 各方数据量 | 均衡 |
| 安全 | 异常更新检测率 | > 95% |
故障恢复
python
class FaultTolerance:
"""故障恢复机制"""
def __init__(self, checkpoint_dir):
self.checkpoint_dir = checkpoint_dir
def save_checkpoint(self, model, round_num, optimizer_state):
"""保存检查点"""
checkpoint = {
"round": round_num,
"model_state": model.state_dict(),
"optimizer_state": optimizer_state,
"timestamp": time.time()
}
path = f"{self.checkpoint_dir}/round_{round_num}.pt"
torch.save(checkpoint, path)
def recover(self, model, target_round=None):
"""从检查点恢复"""
if target_round is None:
# 恢复到最新检查点
checkpoints = sorted(glob(f"{self.checkpoint_dir}/round_*.pt"))
if not checkpoints:
return False
target_round = checkpoints[-1]
checkpoint = torch.load(target_round)
model.load_state_dict(checkpoint["model_state"])
return checkpoint["round"]合规审计
python
class AuditLogger:
"""审计日志"""
def log_round(self, round_num, participants, model_hash):
self.logger.info({
"event": "aggregation_round",
"round": round_num,
"participants": participants,
"model_hash": model_hash,
"timestamp": datetime.now().isoformat()
})
def log_data_access(self, party_id, data_scope, purpose):
self.logger.info({
"event": "data_access",
"party": party_id,
"scope": data_scope,
"purpose": purpose,
"timestamp": datetime.now().isoformat()
})生产部署要点
- 检查点:每 5-10 轮保存,支持恢复
- 超时机制:客户端训练和上传设置超时
- 质量验证:检查更新范数、数值稳定性
- 审计日志:记录所有关键操作
- 灰度发布:新模型先 A/B 测试再全量
生产环境陷阱
- 网络分区:部分客户端可能长时间无法连接
- 版本不一致:客户端和服务端模型版本不同
- 数据漂移:客户端数据分布随时间变化
- 恶意更新:需要鲁棒聚合防御