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

84 lines
3.8 KiB
Python

"""Part A: federated averaging. Your group writes the four functions below.
The server never sees a record. Each round it sends the current model to the
phones, each phone trains that model on its own records (model.local_train),
and the server averages the models that come back. README.md walks through
one round by hand before you write any code.
Python reference: https://docs.python.org/3/library/random.html
"""
import random
import model # noqa: F401 (run_fedavg and train_centralized call model)
def weighted_average(updates):
"""Average several models, weighting each by how many records trained it.
`updates` is a list of (w, b, n): a model's weights, its bias, and the
number of records the phone trained it on. A phone with 80 records counts
twice as much as a phone with 40. Return (w, b).
"""
# YOUR TASK, in four steps (the README's worked round is these steps by hand):
# 1. Add up n over all the updates: the total number of records.
# 2. For each weight position j: multiply every model's w[j] by its n,
# add those products up, and divide by the total.
# 3. Do the same for b.
# 4. Return (w, b).
raise NotImplementedError("weighted_average")
def sample_clients(n_clients, fraction, rng):
"""Pick which phones take part this round. Real systems never reach every phone.
Return a sorted list of round(fraction * n_clients) different phone
numbers from 0 to n_clients - 1, and never fewer than one. Use `rng`
(a random.Random) so a run can be repeated exactly.
"""
# YOUR TASK, in three steps:
# 1. k is fraction * n_clients, rounded, and at least 1.
# 2. Ask rng for k different numbers from range(n_clients) (rng.sample).
# 3. Return them sorted.
raise NotImplementedError("sample_clients")
def run_fedavg(clients, rounds=20, local_epochs=5, lr=0.5, fraction=1.0, seed=0, test=None):
"""Train one model across the phones without collecting their records.
`clients` is a list with one list of records per phone. Start from
model.zeros, then for each round: pick phones with sample_clients, let each
picked phone run model.local_train on its own records starting from the
current model (batch size 8), and replace the current model with the
weighted average of what they return.
Return (w, b, history). When `test` is given, history holds the test
accuracy (model.accuracy) after each round; otherwise it is an empty list.
"""
rng = random.Random(seed) # noqa: F841 (yours to use: sample_clients, local_train)
# YOUR TASK, in four steps:
# 1. Start the server's model: w, b = model.zeros(number of features in one record).
# 2. Start an empty history list.
# 3. Repeat `rounds` times:
# a. Pick this round's phones with sample_clients(len(clients), fraction, rng).
# b. For each picked phone i, train from the current model on that phone's
# records: model.local_train(w, b, clients[i], lr, local_epochs, 8, rng).
# Keep (the new w, the new b, len(clients[i])).
# c. Replace w, b with the weighted_average of what you kept.
# d. If test is given, append model.accuracy(w, b, test) to history.
# 4. Return (w, b, history).
raise NotImplementedError("run_fedavg")
def train_centralized(clients, epochs=20, lr=0.5, seed=0):
"""The baseline federated learning gives up: the server holds every record.
Pool every phone's records into one list and train one model on it with
model.local_train (batch size 8). Return (w, b).
"""
# YOUR TASK, in three steps:
# 1. Put every phone's records into one list.
# 2. Start from model.zeros(number of features in one record).
# 3. Return model.local_train on that list with lr, epochs, batch size 8
# and random.Random(seed).
raise NotImplementedError("train_centralized")