- boot/ (Java/Maven, JNPF 7.0) — 移除旧的 boot/.git,源码直接纳入仓库
- web/ (Vue 3 + Vite + Ant Design Vue, pnpm)
- docs/, scard/, nax/
- refs/INDEX.md + refs/国标/(其余 refs/* 开源子仓库不纳入)
- 已忽略: connector_data/, jweb/, log/, web/{dist,node_modules,.pnpm}, boot/*/target/, .DS_Store, .idea, .vscode
200 lines
8.7 KiB
Python
200 lines
8.7 KiB
Python
"""联邦数据结构与联邦学习算法的端到端测试。"""
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
import pytest
|
|
|
|
import nax
|
|
from nax.data import HFrame, VFrame, intersect, intersect_indices, intersection_size
|
|
from nax.ml import FedAvg, SecureAggregator, VerticalLogisticRegression, linear, metrics
|
|
|
|
|
|
def make_data(n=240, d=6, seed=0):
|
|
rng = np.random.default_rng(seed)
|
|
x = rng.normal(size=(n, d))
|
|
w = rng.normal(size=d)
|
|
y = (rng.random(n) < 1 / (1 + np.exp(-(x @ w)))).astype(float)
|
|
return (x - x.mean(0)) / x.std(0), y
|
|
|
|
|
|
class TestPSI:
|
|
def test_two_party_intersection(self, two_party):
|
|
left = pd.DataFrame({"id": ["a", "b", "c", "d"], "v": [1, 2, 3, 4]})
|
|
right = pd.DataFrame({"id": ["c", "a", "z"], "w": [9, 8, 7]})
|
|
ra = nax.site("alice").put(left)
|
|
rb = nax.site("bob").put(right)
|
|
oa, ob = intersect(ra, rb, "id", "id", seed=0)
|
|
da, db = oa.fetch(force=True), ob.fetch(force=True)
|
|
assert list(da["id"]) == ["a", "c"]
|
|
assert list(db["id"]) == ["a", "c"]
|
|
# 行序对齐:同一行属于同一个 id
|
|
assert list(da["v"]) == [1, 3] and list(db["w"]) == [8, 9]
|
|
|
|
def test_indices_stay_local(self, two_party):
|
|
ra = nax.site("alice").put(pd.DataFrame({"id": ["a", "b"]}))
|
|
rb = nax.site("bob").put(pd.DataFrame({"id": ["b"]}))
|
|
ia, ib = intersect_indices(ra, rb, "id", "id", seed=1)
|
|
assert ia.site == "alice" and ib.site == "bob"
|
|
assert intersection_size(ia) == 1
|
|
|
|
def test_no_overlap(self, two_party):
|
|
ra = nax.site("alice").put(pd.DataFrame({"id": ["a"]}))
|
|
rb = nax.site("bob").put(pd.DataFrame({"id": ["b"]}))
|
|
ia, _ = intersect_indices(ra, rb, "id", "id", seed=2)
|
|
assert intersection_size(ia) == 0
|
|
|
|
def test_audit_records_psi(self, two_party):
|
|
ra = nax.site("alice").put(pd.DataFrame({"id": ["a"]}))
|
|
rb = nax.site("bob").put(pd.DataFrame({"id": ["a"]}))
|
|
intersect_indices(ra, rb, "id", "id", seed=3)
|
|
assert len(nax.audit().filter("psi")) == 1
|
|
|
|
|
|
class TestVFrame:
|
|
def test_align_and_to_secret(self, two_party):
|
|
ids = ["u%d" % i for i in range(10)]
|
|
da = pd.DataFrame({"id": ids[:8], "f1": np.arange(8.0), "f2": np.arange(8.0) * 2})
|
|
db = pd.DataFrame({"id": ids[3:], "f3": np.arange(7.0), "y": [0, 1] * 3 + [1]})
|
|
vf = VFrame({"alice": nax.site("alice").put(da), "bob": nax.site("bob").put(db)})
|
|
aligned = vf.psi_align("id", seed=0)
|
|
assert aligned.count() == 5
|
|
|
|
box = nax.vault(["alice", "bob"], seed=1)
|
|
x = aligned.to_secret(box, drop={"alice": ["id"], "bob": ["id", "y"]})
|
|
assert x.shape == (5, 3)
|
|
got = x.reveal(to="alice").fetch()
|
|
assert np.allclose(got[:, 0], np.arange(3.0, 8.0), atol=1e-3)
|
|
|
|
def test_columns_metadata(self, two_party):
|
|
vf = VFrame({"alice": nax.site("alice").put(pd.DataFrame({"a": [1], "b": [2]}))})
|
|
assert vf.columns()["alice"] == ["a", "b"]
|
|
|
|
|
|
class TestHFrame:
|
|
def test_secure_statistics(self, two_party):
|
|
da = pd.DataFrame({"x": [1.0, 2.0, 3.0], "y": [1.0, 1.0, 1.0]})
|
|
db = pd.DataFrame({"x": [4.0, 5.0], "y": [3.0, 3.0]})
|
|
hf = HFrame({"alice": nax.site("alice").put(da), "bob": nax.site("bob").put(db)})
|
|
box = nax.vault(["alice", "bob"], seed=2)
|
|
assert np.allclose(hf.count(box).fetch(), [5.0], atol=1e-3)
|
|
assert np.allclose(hf.sum(vault=box).fetch(), [15.0, 9.0], atol=1e-2)
|
|
assert np.allclose(hf.mean(vault=box).fetch(), [3.0, 1.8], atol=1e-2)
|
|
allx = np.array([1, 2, 3, 4, 5.0])
|
|
assert np.allclose(hf.var(vault=box).fetch()[0], allx.var(), atol=1e-2)
|
|
|
|
|
|
class TestSecureAggregator:
|
|
@pytest.mark.parametrize("mode", ["mask", "paillier"])
|
|
def test_sum_matches_plain(self, cluster, mode):
|
|
vecs = {
|
|
"alice": np.array([1.0, -2.0, 3.5]),
|
|
"bob": np.array([0.5, 4.0, -1.0]),
|
|
}
|
|
agg = SecureAggregator(
|
|
["alice", "bob"], aggregator="carol", mode=mode,
|
|
key_site=None if mode == "mask" else "alice", paillier_bits=512,
|
|
)
|
|
refs = {s: nax.site(s).put(v) for s, v in vecs.items()}
|
|
out = agg.sum(refs).fetch()
|
|
assert np.allclose(out, vecs["alice"] + vecs["bob"], atol=1e-3)
|
|
|
|
def test_aggregator_sees_only_masked(self, cluster):
|
|
"""聚合方拿到的中间数据必须是掩码态,而不是明文。"""
|
|
agg = SecureAggregator(["alice", "bob"], aggregator="carol", mode="mask")
|
|
refs = {s: nax.site(s).put(np.ones(3)) for s in ["alice", "bob"]}
|
|
agg.sum(refs)
|
|
labels = {e.label for e in nax.audit().filter("transfer")}
|
|
assert "plain" not in labels
|
|
|
|
def test_key_site_cannot_be_aggregator(self, cluster):
|
|
with pytest.raises(nax.ProtocolError):
|
|
SecureAggregator(["alice", "bob"], aggregator="alice",
|
|
mode="paillier", key_site="alice")
|
|
|
|
def test_weighted_average(self, cluster):
|
|
refs = {"alice": nax.site("alice").put(np.array([2.0])),
|
|
"bob": nax.site("bob").put(np.array([4.0]))}
|
|
ws = {"alice": nax.site("alice").put(np.array([3.0])),
|
|
"bob": nax.site("bob").put(np.array([1.0]))}
|
|
agg = SecureAggregator(["alice", "bob"], aggregator="carol")
|
|
out = agg.weighted_average(refs, ws).fetch()
|
|
assert np.allclose(out, (2 * 3 + 4 * 1) / 4, atol=1e-3)
|
|
|
|
|
|
class TestFedAvg:
|
|
def test_converges_close_to_centralized(self, cluster):
|
|
x1, y1 = make_data(200, 5, seed=1)
|
|
x2, y2 = make_data(160, 5, seed=2)
|
|
xs = {"alice": nax.site("alice").put(x1), "bob": nax.site("bob").put(x2)}
|
|
ys = {"alice": nax.site("alice").put(y1), "bob": nax.site("bob").put(y2)}
|
|
fa = FedAvg(["alice", "bob"], aggregator="carol", secure="mask")
|
|
fa.fit(xs, ys, n_features=5, rounds=6, lr=1.0, local_epochs=3)
|
|
|
|
xa, ya = np.vstack([x1, x2]), np.concatenate([y1, y2])
|
|
central = linear.local_train(xa, ya, np.zeros(6), lr=1.0, epochs=18)
|
|
fed_auc = metrics.auc(ya, linear.predict_proba(xa, fa.weights_))
|
|
cen_auc = metrics.auc(ya, linear.predict_proba(xa, central))
|
|
assert fed_auc > 0.7
|
|
assert abs(fed_auc - cen_auc) < 0.05
|
|
assert len(fa.history.rounds) == 6
|
|
|
|
def test_client_mismatch_rejected(self, cluster):
|
|
x, y = make_data(20, 3)
|
|
with pytest.raises(nax.ProtocolError):
|
|
FedAvg(["alice", "bob"], aggregator="carol").fit(
|
|
{"alice": nax.site("alice").put(x)},
|
|
{"alice": nax.site("alice").put(y)},
|
|
n_features=3,
|
|
)
|
|
|
|
|
|
class TestVerticalLR:
|
|
def test_matches_plaintext_training(self, two_party):
|
|
x, y = make_data(200, 4, seed=3)
|
|
box = nax.vault(["alice", "bob"], seed=4)
|
|
xs = box.concat(
|
|
[
|
|
box.share(nax.site("alice").put(x[:, :2])),
|
|
box.share(nax.site("bob").put(x[:, 2:])),
|
|
],
|
|
axis=1,
|
|
)
|
|
ys = box.share(nax.site("bob").put(y.reshape(-1, 1)))
|
|
model = VerticalLogisticRegression(box, lr=1.0, epochs=12, sigmoid_degree=3).fit(xs, ys)
|
|
w = model.weights(to="bob").fetch().reshape(-1)
|
|
w_plain = linear.local_train(x, y, np.zeros(5), lr=1.0, epochs=12)
|
|
assert np.corrcoef(w, w_plain)[0, 1] > 0.99
|
|
|
|
# 密文推理的 AUC 应当贴住明文基线。这里比的是「MPC 是否等价于明文」,
|
|
# 而不是模型本身有多强——标签是按 sigmoid 概率伯努利采样的,
|
|
# 贝叶斯上限本来就不高(约 0.71)。
|
|
prob = model.predict_proba(xs).reveal(to="bob").fetch().reshape(-1)
|
|
auc_secure = metrics.auc(y, prob)
|
|
auc_plain = metrics.auc(y, linear.predict_proba(x, w_plain))
|
|
assert auc_secure == pytest.approx(auc_plain, abs=0.02)
|
|
|
|
def test_weights_stay_secret_until_revealed(self, two_party):
|
|
x, y = make_data(60, 3, seed=5)
|
|
box = nax.vault(["alice", "bob"], seed=6)
|
|
xs = box.share(nax.site("alice").put(x))
|
|
ys = box.share(nax.site("bob").put(y.reshape(-1, 1)))
|
|
model = VerticalLogisticRegression(box, epochs=2, sigmoid_degree=3).fit(xs, ys)
|
|
assert sorted(model.w_.shares) == ["alice", "bob"]
|
|
assert model.w_.shape == (4, 1)
|
|
|
|
|
|
class TestMetrics:
|
|
def test_auc_perfect_and_random(self):
|
|
y = np.array([0, 0, 1, 1.0])
|
|
assert metrics.auc(y, np.array([0.1, 0.2, 0.8, 0.9])) == 1.0
|
|
assert metrics.auc(y, np.array([0.9, 0.8, 0.2, 0.1])) == 0.0
|
|
|
|
def test_auc_ties(self):
|
|
y = np.array([0, 1.0])
|
|
assert metrics.auc(y, np.array([0.5, 0.5])) == 0.5
|
|
|
|
def test_accuracy_and_logloss(self):
|
|
y = np.array([1, 0.0])
|
|
assert metrics.accuracy(y, np.array([0.9, 0.1])) == 1.0
|
|
assert metrics.log_loss(y, np.array([0.5, 0.5])) == pytest.approx(0.6931, abs=1e-3)
|