Files
ssw-mvp/nax/tests/test_aggregators.py
T
admin 3247e9fd15 init: ssw-mvp initial commit
- 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
2026-08-05 18:29:12 +08:00

223 lines
9.7 KiB
Python
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.
"""可组合聚合责任链的测试。
关注三件事:
1. **组合是否正确** —— 每一环单独看对不对,串起来顺序对不对;
2. **护栏是否生效** —— 配错了要报错,而不是悄悄给出一个没有意义的结果;
3. **隐私是否守住** —— 中间量不能以明文经过聚合方。
"""
import numpy as np
import pytest
import nax
from nax.errors import ProtocolError
from nax.ml import FedAvg, linear, metrics
from nax.ml.aggregators import (
Clipping,
GaussianNoise,
Mean,
SecureSum,
Zeroing,
build_chain,
)
from nax.privacy.dp import GaussianAccountant
def put(vals):
return {s: nax.site(s).put(np.asarray(v, dtype=np.float64)) for s, v in vals.items()}
def leaf(cluster_clients=("alice", "bob"), aggregator="carol", **kw):
return SecureSum(list(cluster_clients), aggregator, **kw)
class TestComposition:
def test_plain_sum(self, cluster):
chain = leaf()
refs = put({"alice": [1.0, -2.0, 3.5], "bob": [0.5, 4.0, -1.0]})
out = chain.aggregate(refs).fetch()
assert np.allclose(out, [1.5, 2.0, 2.5], atol=1e-3)
def test_unweighted_mean(self, cluster):
chain = Mean(leaf())
refs = put({"alice": [2.0, 4.0], "bob": [4.0, 8.0]})
assert np.allclose(chain.aggregate(refs).fetch(), [3.0, 6.0], atol=1e-3)
def test_weighted_mean_matches_numpy(self, cluster):
chain = Mean(leaf())
refs = put({"alice": [2.0], "bob": [4.0]})
ws = put({"alice": [3.0], "bob": [1.0]})
out = chain.aggregate(refs, ws).fetch()
assert np.allclose(out, (2 * 3 + 4 * 1) / 4, atol=1e-3)
def test_clipping_bounds_each_client(self, cluster):
"""bob 的向量范数是 100,裁到 1 之后总和的范数不可能超过 2。"""
chain = Clipping(1.0, leaf())
refs = put({"alice": [0.6, 0.8], "bob": [60.0, 80.0]})
out = np.asarray(chain.aggregate(refs).fetch())
assert np.linalg.norm(out) <= 2.0 + 1e-3
# alice 本来就在球内,原样保留;bob 被按比例缩到单位球面上
assert np.allclose(out, [1.2, 1.6], atol=1e-3)
def test_zeroing_drops_the_outlier(self, cluster):
chain = Mean(Zeroing(10.0, leaf(), report_count=False))
refs = put({"alice": [1.0, 2.0], "bob": [300.0, 400.0]})
out = np.asarray(chain.aggregate(refs).fetch())
# bob 整个被丢掉,剩下 alice 一个人参与平均(分母仍是 2)
assert np.allclose(out, [0.5, 1.0], atol=1e-3)
def test_zeroing_reports_count_not_identity(self, cluster):
chain = Zeroing(10.0, leaf())
refs = put({"alice": [1.0, 2.0], "bob": [300.0, 400.0]})
chain.aggregate(refs)
assert chain.measurements["zeroed_clients"] == pytest.approx(1.0, abs=1e-3)
# 计数本身也走安全求和:聚合方拿不到任何一方的明文标志位
labels = {e.label for e in nax.audit().filter("transfer")}
assert "plain" not in labels
def test_chain_order_is_zero_then_clip(self, cluster):
"""置零在裁剪之前:范数 300 的客户端应该被丢掉,而不是被裁到 1。"""
chain = Zeroing(50.0, Clipping(1.0, leaf()), report_count=False)
refs = put({"alice": [0.6, 0.8], "bob": [180.0, 240.0]})
out = np.asarray(chain.aggregate(refs).fetch())
assert np.allclose(out, [0.6, 0.8], atol=1e-3) # 只剩 alice,且它本就在球内
def test_describe_renders_dataflow_order(self, cluster):
chain = build_chain(
["alice", "bob"], "carol", zeroing=10.0, clip=1.0, noise_multiplier=1.0
)
assert chain.describe().startswith("zero(10) → clip(1) → secure_sum(mask) → mean → gaussian")
def test_leaf_and_find(self, cluster):
inner = leaf()
chain = GaussianNoise(1.0, Clipping(2.0, Mean(inner)))
assert chain.leaf() is inner
assert isinstance(chain.find(Clipping), Clipping)
assert chain.find(Zeroing) is None
assert chain.clients == ["alice", "bob"]
assert chain.aggregator == "carol"
class TestDifferentialPrivacy:
def test_noise_std_formula(self, cluster):
chain = GaussianNoise(1.5, Clipping(2.0, Mean(leaf())))
# σ = nm · 2C / n = 1.5 · 4 / 2
assert chain.std == pytest.approx(3.0)
def test_noise_actually_perturbs(self, cluster):
refs = put({"alice": [1.0, 1.0], "bob": [1.0, 1.0]})
clean = Clipping(2.0, Mean(leaf())).aggregate(refs).fetch()
noisy = GaussianNoise(1.0, Clipping(2.0, Mean(leaf())), seed=3).aggregate(refs).fetch()
assert not np.allclose(clean, noisy, atol=1e-6)
def test_refuses_noise_without_clipping(self, cluster):
with pytest.raises(ProtocolError, match="没有裁剪就没有敏感度上界"):
GaussianNoise(1.0, Mean(leaf()), clip=1.0)
def test_explicit_override_allowed(self, cluster):
chain = GaussianNoise(1.0, Mean(leaf()), clip=1.0, require_clipping=False)
assert chain.std > 0
def test_needs_a_clip_value(self, cluster):
with pytest.raises(ProtocolError, match="需要知道裁剪阈值"):
GaussianNoise(1.0, Mean(leaf()))
def test_accountant_advances_per_round(self, cluster):
acc = GaussianAccountant()
chain = GaussianNoise(1.0, Clipping(1.0, Mean(leaf())), accountant=acc)
refs = put({"alice": [1.0], "bob": [1.0]})
chain.aggregate(refs, salt=1)
eps1 = acc.get_epsilon(1e-5)
chain.aggregate(refs, salt=2)
assert acc.get_epsilon(1e-5) > eps1
assert chain.measurements["dp_steps"] == 2.0
class TestGuardrails:
def test_secure_sum_refuses_weights(self, cluster):
refs = put({"alice": [1.0], "bob": [1.0]})
with pytest.raises(ProtocolError, match="套一层 Mean"):
leaf().aggregate(refs, refs)
def test_build_chain_rejects_low_zeroing(self, cluster):
with pytest.raises(ProtocolError, match="置零在裁剪之前发生"):
build_chain(["alice", "bob"], "carol", zeroing=0.5, clip=1.0)
def test_build_chain_rejects_noise_without_clip(self, cluster):
with pytest.raises(ProtocolError, match="敏感度无界"):
build_chain(["alice", "bob"], "carol", noise_multiplier=1.0)
def test_rejects_nonpositive_thresholds(self, cluster):
with pytest.raises(ProtocolError, match="裁剪阈值必须为正"):
Clipping(0.0, leaf())
with pytest.raises(ProtocolError, match="置零阈值必须为正"):
Zeroing(-1.0, leaf())
with pytest.raises(ProtocolError, match="噪声乘数必须为正"):
GaussianNoise(0.0, Clipping(1.0, leaf()))
def test_weight_site_mismatch(self, cluster):
chain = Mean(leaf())
refs = put({"alice": [1.0], "bob": [1.0]})
ws = {"alice": nax.site("alice").put(np.array([1.0]))}
with pytest.raises(ProtocolError, match="权重的参与方集合"):
chain.aggregate(refs, ws)
def make_data(n=240, d=5, 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 TestFedAvgIntegration:
def test_default_chain_shape(self, cluster):
fa = FedAvg(["alice", "bob"], aggregator="carol")
assert fa.aggregation.describe() == "secure_sum(mask) → mean"
assert fa.accountant is None
assert fa.dp_enabled is False
def test_dp_chain_shape(self, cluster):
fa = FedAvg(["alice", "bob"], "carol", dp_clip=1.0, dp_noise_multiplier=1.5)
assert fa.aggregation.describe().startswith("clip(1) → secure_sum(mask) → mean → gaussian")
assert fa.dp_enabled and fa.accountant is not None
def test_custom_chain_accepted(self, cluster):
chain = Mean(Clipping(2.0, SecureSum(["alice", "bob"], "carol")))
fa = FedAvg(["alice", "bob"], "carol", aggregation=chain)
assert fa.aggregation is chain
assert fa.dp_enabled is False
def test_custom_chain_conflicts_with_knobs(self, cluster):
chain = Mean(SecureSum(["alice", "bob"], "carol"))
with pytest.raises(ProtocolError, match="别再传"):
FedAvg(["alice", "bob"], "carol", aggregation=chain, dp_clip=1.0)
def test_zeroing_measurements_land_in_history(self, cluster):
x1, y1 = make_data(120, 5, seed=1)
x2, y2 = make_data(100, 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"], "carol", zeroing=100.0)
fa.fit(xs, ys, n_features=5, rounds=2, lr=0.5, local_epochs=1)
assert len(fa.history.measurements) == 2
# 正常训练不该有人被置零
assert all(m["zeroed_clients"] == pytest.approx(0.0, abs=1e-3)
for m in fa.history.measurements)
def test_delta_space_matches_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"], "carol").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 abs(fed_auc - cen_auc) < 0.05