federated-learning/experiments.py
2026-11-08 17:17:54 -07:00

151 lines
6.1 KiB
Python

"""Run all three parts and print the tables for your report. Given; you do not change this file.
python3 experiments.py # everything that is written so far
python3 experiments.py A # one part
It also writes results.json, so you can quote exact numbers. A part whose
functions are not written yet is skipped with a note rather than crashing,
so the group can run it from the first day.
"""
import json
import random
import sys
import data
import defend
import fedavg
import leak
import model
SEED = 7
def part_a(clients, test, out):
print("\n## Part A: federated averaging\n")
w, b = fedavg.train_centralized(clients, seed=SEED)
central = model.accuracy(w, b, test)
alone = []
for c in clients:
lw, lb = model.local_train(*model.zeros(4), c, 0.5, 20, 8, random.Random(SEED))
alone.append(model.accuracy(lw, lb, test))
_w, _b, hist = fedavg.run_fedavg(clients, rounds=20, seed=SEED, test=test)
_w, _b, half = fedavg.run_fedavg(clients, rounds=20, fraction=0.5, seed=SEED, test=test)
print("| Setup | Test accuracy |\n| :--- | --: |")
print(f"| Server holds every record (centralized) | {central:.3f} |")
print(f"| One phone training alone (average of 10) | {sum(alone) / len(alone):.3f} |")
print(f"| One phone alone, worst / best | {min(alone):.3f} / {max(alone):.3f} |")
print(f"| FedAvg, all phones, after 20 rounds | {hist[-1]:.3f} |")
print(f"| FedAvg, half the phones each round | {half[-1]:.3f} |")
print("\nFedAvg accuracy by round: " + ", ".join(f"{a:.2f}" for a in hist))
out["A"] = {
"centralized": central,
"alone": alone,
"fedavg_by_round": hist,
"fedavg_half": half,
}
def part_b(clients, test, out):
print("\n## Part B: what one update leaks\n")
w, b, _ = fedavg.run_fedavg(clients, rounds=3, seed=SEED) # the model the server sent out
rng = random.Random(SEED)
phone = clients[3]
x, y = phone[0]
x_hat = leak.reconstruct(*leak.observe_update(w, b, [(x, y)]))
print("One update from one record:\n")
print(f"- the record: {data.describe(x)}")
seen = data.describe(x_hat) if x_hat else "(nothing recoverable)"
print(f"- what server saw: {seen}\n")
print(
"| Records per update | Mean error of best match | Recovered to within 0.01 |\n"
"| --: | --: | --: |"
)
rows = {}
for size in (1, 2, 4, 8, 16):
errs = []
for _ in range(100):
batch = rng.sample(phone, size)
x_hat = leak.reconstruct(*leak.observe_update(w, b, batch))
errs.append(leak.best_match_error(batch, x_hat))
exact = sum(e < 0.01 for e in errs) / len(errs)
finite = [e for e in errs if e != float("inf")]
mean = sum(finite) / len(finite) if finite else float("inf")
rows[size] = {"mean_error": mean, "within_0.01": exact}
print(f"| {size} | {mean:.3f} | {exact:.0%} |")
out["B"] = rows
def part_c(clients, test, out):
print("\n## Part C: defenses and what they cost\n")
w, b, _ = fedavg.run_fedavg(clients, rounds=3, seed=SEED)
rng = random.Random(SEED)
phone = clients[3]
print("Clip to length 1, then add noise, to a one-record update:\n")
print(
"| Noise sigma | Mean reconstruction error "
"| FedAvg accuracy with this noise on every update |\n"
"| --: | --: | --: |"
)
rows = {}
for sigma in (0.0, 0.01, 0.05, 0.1, 0.5):
errs = []
for x, y in phone:
dw, db = defend.clip(*leak.observe_update(w, b, [(x, y)]), 1.0)
dw, db = defend.add_noise(dw, db, sigma, rng)
errs.append(leak.best_match_error([(x, y)], leak.reconstruct(dw, db)))
finite = [e for e in errs if e != float("inf")]
acc = _noisy_fedavg(clients, test, sigma)
rows[sigma] = {"mean_error": sum(finite) / len(finite), "accuracy": acc}
print(f"| {sigma} | {rows[sigma]['mean_error']:.3f} | {acc:.3f} |")
vectors = [defend.flatten(*leak.observe_update(w, b, [r])) for r in (c[0] for c in clients)]
masked = defend.mask_updates(vectors, seed=SEED)
plain = [sum(col) for col in zip(*vectors)]
got = defend.secure_sum(masked)
drift = max(abs(a - c) for a, c in zip(plain, got))
alone = leak.best_match_error([clients[0][0]], leak.reconstruct(*defend.unflatten(masked[0])))
print("\nSecure aggregation, ten phones, one record each:\n")
print(f"- largest difference between the masked sum and the true sum: {drift:.2e}")
print(f"- error reconstructing phone 0 from its masked update alone: {alone:.3f}")
unmasked = leak.reconstruct(*defend.unflatten(vectors[0]))
unmasked_error = leak.best_match_error([clients[0][0]], unmasked)
print(f"- error reconstructing phone 0 from its update without masking: {unmasked_error:.3f}")
out["C"] = {"noise": rows, "secure_sum_drift": drift, "masked_single_error": alone}
def _noisy_fedavg(clients, test, sigma, rounds=20):
"""FedAvg where every phone clips and noises its update before sending it."""
rng = random.Random(SEED)
w, b = model.zeros(4)
for _ in range(rounds):
deltas = []
for c in clients:
lw, lb = model.local_train(w, b, c, 0.5, 5, 8, rng)
dw, db = [a - g for a, g in zip(lw, w)], lb - b
dw, db = defend.clip(dw, db, 1.0)
dw, db = defend.add_noise(dw, db, sigma, rng)
deltas.append((dw, db, len(c)))
aw, ab = fedavg.weighted_average(deltas)
w, b = [g + a for g, a in zip(w, aw)], b + ab
return model.accuracy(w, b, test)
def main():
clients, test = data.make_clients(), data.make_test_set()
wanted = sys.argv[1:] or ["A", "B", "C"]
out = {}
for name, fn in (("A", part_a), ("B", part_b), ("C", part_c)):
if name not in wanted:
continue
try:
fn(clients, test, out)
except NotImplementedError as e:
print(f"\n## Part {name}: skipped, not written yet ({e})")
with open("results.json", "w") as f:
json.dump(out, f, indent=1)
print("\nwrote results.json")
if __name__ == "__main__":
main()