171 lines
6.2 KiB
Python
171 lines
6.2 KiB
Python
"""Check your functions before you run the experiments. Given; you do not change this file.
|
|
|
|
python3 selfcheck.py
|
|
|
|
Each check prints PASS, FAIL (with what it expected), or SKIP when the
|
|
function still raises NotImplementedError. Passing every check means your
|
|
functions do what the README asks. It does not grade your report.
|
|
"""
|
|
|
|
import math
|
|
import random
|
|
|
|
import data
|
|
import defend
|
|
import fedavg
|
|
import leak
|
|
import model
|
|
|
|
results = []
|
|
|
|
|
|
def check(name, fn):
|
|
try:
|
|
fn()
|
|
results.append("PASS")
|
|
print(f"PASS {name}")
|
|
except NotImplementedError:
|
|
results.append("SKIP")
|
|
print(f"SKIP {name} (not written yet)")
|
|
except AssertionError as e:
|
|
results.append("FAIL")
|
|
print(f"FAIL {name}: {e}")
|
|
|
|
|
|
def close(a, b, tol=1e-9):
|
|
return abs(a - b) <= tol
|
|
|
|
|
|
# Part A
|
|
|
|
def a_weighted_average():
|
|
w, b = fedavg.weighted_average([([1.0, 0.0], 2.0, 10), ([4.0, 3.0], 5.0, 20)])
|
|
assert all(close(g, e) for g, e in zip(w, [3.0, 2.0])) and close(b, 4.0), (
|
|
f"models (w=[1,0], b=2, 10 records) and (w=[4,3], b=5, 20 records) "
|
|
f"should average to w=[3, 2], b=4, got w={w}, b={b}")
|
|
|
|
|
|
def a_single_update():
|
|
w, b = fedavg.weighted_average([([0.5, -1.0], 0.25, 7)])
|
|
assert w == [0.5, -1.0] and b == 0.25, "averaging one model must return that model"
|
|
|
|
|
|
def a_sample_clients():
|
|
picked = fedavg.sample_clients(10, 0.5, random.Random(1))
|
|
assert len(picked) == 5, f"half of 10 phones is 5, got {len(picked)}"
|
|
assert len(set(picked)) == 5 and all(0 <= i < 10 for i in picked), (
|
|
f"expected 5 different phone numbers from 0 to 9, got {picked}")
|
|
picked_one = fedavg.sample_clients(10, 0.01, random.Random(1))
|
|
assert len(picked_one) == 1, "at least one phone every round"
|
|
|
|
|
|
def a_run_fedavg_learns():
|
|
clients, test = data.make_clients(), data.make_test_set()
|
|
w, b, hist = fedavg.run_fedavg(clients, rounds=10, seed=1, test=test)
|
|
assert len(hist) == 10, f"history should have one accuracy per round, got {len(hist)}"
|
|
assert hist[-1] > 0.75, (
|
|
f"after 10 rounds test accuracy should pass 0.75, got {hist[-1]:.3f}")
|
|
no_test_hist = fedavg.run_fedavg(clients, rounds=2, seed=1)[2]
|
|
assert len(no_test_hist) == 0, "no test set means empty history"
|
|
|
|
|
|
def a_centralized():
|
|
clients, test = data.make_clients(), data.make_test_set()
|
|
w, b = fedavg.train_centralized(clients)
|
|
acc = model.accuracy(w, b, test)
|
|
assert acc > 0.8, f"training on every record should pass 0.8 accuracy, got {acc:.3f}"
|
|
|
|
|
|
# Part B
|
|
|
|
W, B = [0.3, -0.2, 0.1, 0.4], -0.1
|
|
REC = ([0.4, 0.7, 0.2, 0.9], 1)
|
|
|
|
|
|
def b_observe():
|
|
dw, db = leak.observe_update(W, B, [REC])
|
|
ew, eb = model.gradient(W, B, [REC])
|
|
assert close(db, eb) and all(close(g, e) for g, e in zip(dw, ew)), (
|
|
"a one-step update on a batch should be model.gradient on that batch")
|
|
|
|
|
|
def b_reconstruct_one():
|
|
x_hat = leak.reconstruct(*leak.observe_update(W, B, [REC]))
|
|
assert x_hat is not None, "an update from one record should be reconstructable"
|
|
err = leak.reconstruction_error(REC[0], x_hat)
|
|
assert err < 1e-9, f"one record should come back exactly, off by {err}"
|
|
|
|
|
|
def b_reconstruct_zero():
|
|
assert leak.reconstruct([0.0, 0.0, 0.0, 0.0], 0.0) is None, (
|
|
"an all-zero update carries nothing to recover: return None")
|
|
|
|
|
|
def b_errors():
|
|
assert close(leak.reconstruction_error([0, 0, 0, 0], [1, -1, 0.5, -0.5]), 0.75), (
|
|
"reconstruction_error is the mean absolute difference")
|
|
batch = [([0, 0, 0, 0], 1), ([1, 1, 1, 1], 0)]
|
|
assert close(leak.best_match_error(batch, [0.9, 1, 1, 1]), 0.025), (
|
|
"best_match_error is the error against the closest record in the batch")
|
|
assert leak.best_match_error(batch, None) == math.inf, "no reconstruction means infinite error"
|
|
|
|
|
|
# Part C
|
|
|
|
def c_clip():
|
|
dw, db = defend.clip([3.0, 0.0], 4.0, 1.0)
|
|
assert close(dw[0], 0.6) and close(dw[1], 0.0) and close(db, 0.8), (
|
|
f"([3, 0], 4) has length 5; clipped to 1 it is ([0.6, 0], 0.8), got ({dw}, {db})")
|
|
short = defend.clip([0.1, 0.2], 0.2, 1.0)
|
|
assert short == ([0.1, 0.2], 0.2), "a short update comes back unchanged"
|
|
|
|
|
|
def c_noise():
|
|
rng = random.Random(3)
|
|
samples = [defend.add_noise([0.0], 0.0, 0.5, rng) for _ in range(4000)]
|
|
vals = [dw[0] for dw, _db in samples] + [db for _dw, db in samples]
|
|
mean = sum(vals) / len(vals)
|
|
sd = math.sqrt(sum((v - mean) ** 2 for v in vals) / len(vals))
|
|
assert abs(mean) < 0.05 and abs(sd - 0.5) < 0.05, (
|
|
f"noise should average 0 with spread sigma=0.5, got mean {mean:.3f}, sd {sd:.3f}")
|
|
assert defend.add_noise([1.0], 2.0, 0.0, rng) == ([1.0], 2.0), "sigma 0 adds nothing"
|
|
|
|
|
|
def c_flatten():
|
|
v = defend.flatten([1.0, 2.0], 3.0)
|
|
assert v == [1.0, 2.0, 3.0], f"flatten([1, 2], 3) should be [1, 2, 3], got {v}"
|
|
assert defend.unflatten(v) == ([1.0, 2.0], 3.0), "unflatten should undo flatten"
|
|
|
|
|
|
def c_secure_sum():
|
|
vectors = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]
|
|
masked = defend.mask_updates(vectors, seed=11)
|
|
got = defend.secure_sum(masked)
|
|
assert all(close(g, e, 1e-6) for g, e in zip(got, [12.0, 15.0, 18.0])), (
|
|
f"masks must cancel: the sum should be [12, 15, 18], got {got}")
|
|
assert all(abs(a - b) > 1e-3 for a, b in zip(masked[0], vectors[0])), (
|
|
"each masked vector must differ from the phone's real update")
|
|
again = defend.mask_updates(vectors, seed=11)
|
|
assert again == masked, "the same seed must give the same masks"
|
|
|
|
|
|
for name, fn in [
|
|
("A weighted_average weights by record count", a_weighted_average),
|
|
("A weighted_average of one model", a_single_update),
|
|
("A sample_clients", a_sample_clients),
|
|
("A run_fedavg learns", a_run_fedavg_learns),
|
|
("A train_centralized", a_centralized),
|
|
("B observe_update", b_observe),
|
|
("B reconstruct one record", b_reconstruct_one),
|
|
("B reconstruct an empty update", b_reconstruct_zero),
|
|
("B error measures", b_errors),
|
|
("C clip", c_clip),
|
|
("C add_noise", c_noise),
|
|
("C flatten and unflatten", c_flatten),
|
|
("C mask_updates and secure_sum", c_secure_sum),
|
|
]:
|
|
check(name, fn)
|
|
|
|
passed, failed, skipped = (results.count(r) for r in ("PASS", "FAIL", "SKIP"))
|
|
print(f"\n{passed} passed, {failed} failed, {skipped} not written yet")
|
|
raise SystemExit(1 if "FAIL" in results else 0)
|