"""Part C: two defenses, and what each costs. Your group writes three functions below. Clipping plus noise is the recipe behind differentially private federated learning (the Laplace mechanism project uses the same idea on counts). Secure aggregation is a different kind of defense: it hides each phone's update behind masks that cancel when the server adds them up. Python reference: https://docs.python.org/3/library/random.html#random.Random.gauss """ import math # noqa: F401 (clip needs math.sqrt) import random # noqa: F401 (mask_updates needs random.Random) def flatten(dw, db): """An update as one list of numbers: the weights, then the bias.""" return list(dw) + [db] def unflatten(v): """Undo flatten: a list of numbers back into (dw, db).""" return list(v[:-1]), v[-1] def clip(dw, db, max_norm): """Shrink an update, if needed, so its length is at most max_norm. Length means the Euclidean (L2) length of flatten(dw, db): the square root of the sum of every number squared. A longer update is scaled down, every number by the same factor, until its length is exactly max_norm. An update already within the limit comes back unchanged. Return (dw, db). """ # YOUR TASK, in five steps: # 1. v = flatten(dw, db). # 2. The length is the square root of the sum of every number in v squared. # 3. If the length is at most max_norm, or is 0, return (list(dw), db) unchanged. # 4. Otherwise multiply every number in v by max_norm / length. # 5. Return unflatten of the scaled list. raise NotImplementedError("clip") def add_noise(dw, db, sigma, rng): """Add independent Gaussian noise, standard deviation sigma, to every number. Use rng.gauss(0.0, sigma) once per number. Return (dw, db). """ # YOUR TASK, in three steps (keep this order, so runs repeat exactly): # 1. For each number in dw, add rng.gauss(0.0, sigma). # 2. Add one more rng.gauss(0.0, sigma) to db. # 3. Return (the new dw, the new db). raise NotImplementedError("add_noise") def mask_updates(vectors, seed): """Secure aggregation by pairwise masking. `vectors` holds one flattened update per phone. For every pair of phones i < j, both make the same random mask from a seed only the two of them share, random.Random(f"{seed}-{i}-{j}"), drawing one rng.gauss(0.0, 10.0) per number. Phone i adds the mask to its update and phone j subtracts it. Return the masked vectors, one per phone, in the same order. """ # YOUR TASK, in four steps: # 1. Copy every vector, so the originals are not changed. # 2. For every pair of phones i < j, make rng = random.Random(f"{seed}-{i}-{j}") # and draw the mask: one rng.gauss(0.0, 10.0) per number. # 3. Add the mask to phone i's copy and subtract it from phone j's copy. # 4. Return the copies, one per phone, in the same order. raise NotImplementedError("mask_updates") def secure_sum(masked): """What the server computes: the number-by-number sum of what it received.""" return [sum(col) for col in zip(*masked)]