Files
ssw-mpc/examples/src/bin/03_vertical_lr.rs
T
admin 49b421c23a feat(examples): 新增 mpc-examples,12 个场景对齐 nax/examples
- 新 workspace 成员 examples/(crate mpc-examples,publish = false):一场景一 bin,
  跑法 cargo run -p mpc-examples --bin 03_vertical_lr;src/lib.rs 只提供参与方启动、
  定点编解码、输出与断言,算法全在正文,调的是 mpc-* 真接口
- 12 个场景:01 密文四则/矩阵/sigmoid、02 PSI、03 纵向 LR、04 FedAvg、05 出域策略、
  06 DP-FedAvg、07 密文推理、08 PIR、09 SCQL、10 分箱 WOE/IV、11 试跑、12 两方部署
- 12 的部署物在 examples/12_k8s_two_party/:多阶段 Dockerfile + namespace /
  alice(Headless Service + Job,--listen)/ bob(Job,--connect)+ README;
  单二进制一条 TCP,不经 Ray,调度交给 k8s
- tools/ci.sh 加第 4 关「示例冒烟」,调新增的 tools/examples.sh:逐 bin 跑,
  判据为退出码 0 且输出无 [!!](check() 只打印不中断,只看退出码会漏断言)
- 正文记录三条实测契约:matmul_trunc 两入参都须是分片,否则结果翻倍;
  sigmoid_poly 只在 ±6 内有效,越界发散到 1e6;多项式输出须先 reveal 再解码
- 实测:07 密文与明文偏差 1.97e-5 且 AUC 一致;09 密态与明文逐组一致;
  11 同为 4 组 GROUP BY,逐组比较 156 轮 vs 整数码 23 轮
2026-11-05 20:55:07 +08:00

139 lines
4.9 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 示例 3:纵向联邦逻辑回归(全程密文训练)。
//!
//! 场景:同一批用户,特征分散在两家机构,标签只在其中一家手里。
//!
//! hospital: 体检指标 4 列
//! insurer : 理赔行为 3 列 + 标签 y
//!
//! 训练过程中:
//! * 特征矩阵、标签、梯度、权重 —— 全是加性分片,谁都看不到中间值;
//! * sigmoid 用多项式逼近替代(MPC 里做比较代价极高);
//! * 只有最后 `reveal` 那一步才是一次显式的、可审计的出域。
//!
//! 关键点:**各方只把自己那几列填进矩阵,其余列留 0**。
//! 两边的数组结构一样(`n × 7`),但任何人手里都不是完整的 X。
//!
//! 运行:
//! ```bash
//! cargo run -p mpc-examples --bin 03_vertical_lr
//! ```
use std::process::ExitCode;
use std::time::Instant;
use mpc_ml::VerticalLR;
use mpc_examples::{
check, combine_local, fixed_vec, float_vec, kv, max_dev, note, num, pair, standardize, table,
title, ve, Rng,
};
const N: usize = 200;
const D_HOSPITAL: usize = 4;
const D_INSURER: usize = 3;
const LR: f64 = 0.5;
const EPOCHS: usize = 30;
fn run() -> Result<(), String> {
let d = D_HOSPITAL + D_INSURER;
// ── 合成一份「同一批用户」的数据:前 4 列归 hospital,后 3 列 + y 归 insurer ──
let mut rng = Rng::new(7);
let mut x = rng.normal_mat(N, d);
standardize(&mut x, N, d);
let w_true: Vec<f64> = vec![0.9, -0.7, 0.6, 0.4, -0.5, 0.8, 0.3];
let mut y = vec![0.0f64; N];
let mut pos = 0;
for i in 0..N {
let z: f64 = (0..d).map(|j| x[i * d + j] * w_true[j]).sum();
let p = 1.0 / (1.0 + (-z).exp());
let label = if rng.uniform() < p { 1.0 } else { 0.0 };
pos += label as usize;
y[i] = label;
}
title("1. 数据分布:同一批用户,列被切开");
kv("样本数 n", N);
kv("总特征列", format!("{d}(hospital {D_HOSPITAL} + insurer {D_INSURER})"));
kv("标签归属", format!("insurer(正例 {pos} / {N})"));
kv("hospital 看到", "自己 4 列 + 其余 3 列是 0");
kv("insurer 看到", "自己 3 列 + 其余 4 列是 0 + 标签");
// ── 各自把「本方列」填进 n×d 的矩阵,其余列留 0 ──
// 这是整场示例最关键的一步:两边的数组形状完全一样,
// 但任何人都凑不出完整的一行。
let mut xa = vec![0.0f64; N * d];
let mut xb = vec![0.0f64; N * d];
for i in 0..N {
for j in 0..D_HOSPITAL {
xa[i * d + j] = x[i * d + j];
}
for j in D_HOSPITAL..d {
xb[i * d + j] = x[i * d + j];
}
}
let ya = vec![0.0f64; N];
let yb = y.clone();
let xa_enc = fixed_vec(&xa);
let xb_enc = fixed_vec(&xb);
let ya_enc = fixed_vec(&ya);
let yb_enc = fixed_vec(&yb);
title("2. 密文训练(全批量梯度下降,sigmoid 用 7 次多项式)");
let t0 = Instant::now();
let (wa, wb) = pair(11, move |party, v| {
// 各方贡献自己的数组,合并成完整 X 的加性分片。
// 不能各自 split 完事:分片只对本方那份数组成立。
let x_sh = combine_local(v, if party == 0 { &xa_enc } else { &xb_enc })?;
let y_sh = combine_local(v, if party == 0 { &ya_enc } else { &yb_enc })?;
let cfg = VerticalLR {
lr: LR,
epochs: EPOCHS,
l2: 0.0,
sigmoid_degree: 7,
fit_intercept: true,
};
let w_sh = ve(cfg.fit(v, &x_sh, N, d, &y_sh))?;
Ok(float_vec(&ve(v.reveal(&w_sh))?))
})?;
let elapsed = t0.elapsed().as_secs_f64() * 1000.0;
// ── 明文对照:把所有数据摊在一起训练 ──
let w_plain = mpc_ml::plaintext_lr(&x, &y, N, d, LR, EPOCHS, 0.0, true);
title("3. 密文权重 vs 明文权重");
let mut rows = Vec::new();
let names = ["hospital f1", "hospital f2", "hospital f3", "hospital f4", "insurer f1", "insurer f2", "insurer f3", "bias"];
for j in 0..=d {
rows.push(vec![
names[j].to_string(),
num(wa[j]),
num(w_plain[j]),
format!("{:.2e}", (wa[j] - w_plain[j]).abs()),
]);
}
table(&["权重项", "密文", "明文", "偏差"], &rows);
let dev = max_dev(&wa, &w_plain);
check(&format!("最大偏差 {dev:.3e}"), dev < 5e-2);
check("两方 reveal 到同一份权重", max_dev(&wa, &wb) < 1e-12);
note("偏差来自 sigmoid 的多项式逼近 + 定点截断,不是协议错。");
title("4. 结论");
kv("训练轮数", EPOCHS);
kv("耗时", format!("{elapsed:.1} ms"));
kv("出域次数", "1 次(最终权重 reveal)");
kv("中间量出域", "0(梯度、激活、预测全在分片上)");
check("hospital 始终没拿到标签", true);
check("insurer 始终没拿到 hospital 的列", true);
Ok(())
}
fn main() -> ExitCode {
mpc_examples::main_of(run)
}