federated-learning/leak.py
2026-11-18 11:20:58 -07:00

56 lines
2.4 KiB
Python

"""Part B: what one update tells the server. Your group writes the functions below.
Federated learning keeps the records on the phone, but the phone still sends
something: its update. This part asks how much of a record that update gives
away. Start from the formula in model.gradient's docstring and work out, on
paper, what the server could compute from an update made from ONE record.
Write that derivation in your report before you write reconstruct().
"""
import model # noqa: F401 (observe_update calls model.gradient)
def observe_update(w, b, batch):
"""What the server receives when a phone takes one training step on `batch`.
A phone that takes one step sends the gradient it computed. Return (dw, db).
"""
# YOUR TASK, in one step: the update a phone sends is the gradient of the
# current model on its batch, which model.gradient computes. Return (dw, db).
raise NotImplementedError("observe_update")
def reconstruct(dw, db, eps=1e-12):
"""Recover the record behind an update computed from one record.
Return the recovered features as a list, one number per feature. When the
update carries nothing to recover (db within eps of zero), return None.
"""
# YOUR TASK, in three steps:
# 1. If db is within eps of zero, return None. (Your report says why
# such an update carries nothing to recover.)
# 2. Otherwise, for each feature j, use the relationship between dw[j]
# and db that you worked out on paper for a one-record update.
# 3. Return the list of recovered features.
raise NotImplementedError("reconstruct")
def reconstruction_error(x_true, x_hat):
"""The mean absolute difference between a real record and a reconstruction."""
# YOUR TASK, in two steps:
# 1. For each feature, take the absolute difference between x_true and x_hat.
# 2. Return the average of those differences.
raise NotImplementedError("reconstruction_error")
def best_match_error(batch, x_hat):
"""The attacker's best claim: how close x_hat is to SOME record in the batch.
Return the smallest reconstruction_error between x_hat and any record's
features, or float("inf") when x_hat is None.
"""
# YOUR TASK, in three steps:
# 1. If x_hat is None, return float("inf").
# 2. For each record (x, y) in the batch, compute reconstruction_error(x, x_hat).
# 3. Return the smallest of those.
raise NotImplementedError("best_match_error")