Engineer a federated learning control tower managing cohort selection, device dropout,…
- User
Engineer a federated learning control tower managing cohort selection, device dropout, and update validation.
- Assistant
Engineer a federated learning control tower managing cohort selection, device dropout, and update validation.
We are going to design a federated learning control tower that manages:
We assume a Federated Averaging (FedAvg) like setting, but with the following modifications:
Steps for one round:
Additional considerations:
Let's design classes:
Client: represents a client device. It has:
Server (ControlTower):
We'll also need a communication simulation (since we are designing, we can assume that we have a way to send the model to clients and receive updates, but in practice we have to handle network issues).
Let's define the steps in a round:
Step 1: Select cohort.
- The server selects a cohort of size cohort_size from the available clients.
Step 2: Broadcast the global model to the cohort.
Step 3: Wait for updates from the cohort, with a timeout. - For each client in the cohort, we start a task (asynchronously) and wait for the update. - If a client does not respond within the timeout, we consider it dropped out.
Step 4: Validate each received update. - For each update, we run the update_validator. If it fails, we discard the update.
Step 5: Aggregate the valid updates.
Step 6: Update the global model.
Step 7: Update the server's knowledge about clients (e.g., record if a client dropped out, or if an update was invalid, to adjust future cohort selection).
We'll design the server to be asynchronous in terms of waiting for updates? Actually, in a real system, we might have to handle asynchronous updates. But for simplicity, let's assume we wait for a fixed timeout and then proceed.
However, note: in a real federated learning setting, we might not want to wait too long because of stragglers. So we can set a timeout and then aggregate the updates we have received by then.
Let's design:
class Client: def init(self, client_id, data, model_fn): self.client_id = client_id self.data = data # we assume data has a method to get number of samples and a data loader self.model = model_fn() # local model, initially same as global self.is_available = True # can be set to False to simulate dropout
def train(self, global_weights, epochs=1, batch_size=32):
# set local model weights to global_weights
self.model.set_weights(global_weights)
# train on local data for given epochs
# return the update (difference between local model after training and global_weights)
# Also, we might want to return the number of samples used.
def set_availability(self, available):
self.is_available = available
class ControlTower: def init(self, global_model, available_clients, cohort_size, timeout, update_validator, aggregator): self.global_model = global_model self.available_clients = available_clients # list of Client objects self.cohort_size = cohort_size self.timeout = timeout # in seconds, how long to wait for updates self.update_validator = update_validator self.aggregator = aggregator
However, note: the above approach uses a ThreadPoolExecutor and waits for each future with a timeout of the entire round?
Actually, as_completed with a timeout will raise a TimeoutError if no future completes within the timeout?
But we want to wait for the entire round and then take all the updates that are done by then.
Alternatively, we can set a timeout for each future? But we don't want to wait for a single client too long.
Let me adjust: we want to wait for at most self.timeout seconds for the entire round, and then take whatever updates we have.
The as_completed function with a timeout will wait for at least one future to complete, and then return as they complete, but if the timeout expires and no future has completed, it raises TimeoutError.
But we want to wait for all the futures that complete within the timeout, and then ignore the ones that don't.
We can do:
done, not_done = wait(future_to_client.keys(), timeout=self.timeout, return_when=ALL_COMPLETED)
But then we have to handle the not_done ones (we can cancel them? but again, we can't cancel a running thread).
Alternatively, we can set a timeout for each future? But that would require per-client timeout, which might be what we want?
Actually, we want to give each client the same amount of time? Then we can set a timeout for each future to self.timeout?
However, note: if we set a timeout for each future, then if one client takes 2*timeout, we would have already canceled it? But we can't cancel.
So perhaps we should not use a thread pool for each client? Instead, we could have a separate thread for each client and then use a queue to collect results, and then wait for the queue for self.timeout seconds?
But let's simplify: we are going to assume that the training on each client is fast and we set a timeout for the entire round. We'll use as_completed and then break out when the timeout is reached?
Actually, the as_completed function doesn't let us break out after a total timeout? It waits for each future to complete and returns them as they complete. We can set a timeout for the as_completed iterator?
From the docs: as_completed(fs, timeout=None) returns an iterator that yields futures as they complete. If timeout is specified, it raises TimeoutError if no future completes within timeout.
So we can:
try:
for future in as_completed(future_to_client, timeout=self.timeout):
... process future ...
except TimeoutError:
# No future completed within the timeout? But we might have some that completed already?
# Actually, the iterator will yield futures as they complete, and if the timeout expires, it raises TimeoutError and we break.
pass
But note: the timeout is for the first future? Actually, the timeout is for the entire iterator?
Let me check: the timeout is the maximum time to wait for the first future? Actually, the documentation says: "If timeout is specified, it raises TimeoutError if no future completes within timeout."
So if we have 10 clients and the first one completes at 1 second, then the iterator yields that one and then continues? And if the next one takes 10 seconds, then after 1 second we have one, and then we wait for the next?
But we want to wait for the entire round for at most self.timeout and then take whatever we have. So we don't want to raise an error if one future takes too long?
Alternatively, we can do:
import time
end_time = time.time() + self.timeout
for future in as_completed(future_to_client):
if time.time() > end_time:
break
... process future ...
But then we are breaking out of the loop and leaving the remaining futures运行? We can't cancel them.
Given the complexity, and since we are simulating, let's assume that we set a per-client timeout?
Actually, we can set a timeout for each future when we call future.result(timeout=?)? But we are using as_completed which doesn't let us set a timeout per future.
Another approach: we can use wait with a timeout and a condition?
Let's change the design:
We want to wait for a maximum of `self.timeout` seconds for the entire round, and then aggregate the updates we have.
We can do:
from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED
futures = [executor.submit(client.train, global_weights) for client in cohort if client.is_available]
# Wait for the first future to complete, or until timeout
done, not_done = wait(futures, timeout=self.timeout, return_when=FIRST_COMPLETED)
# Then, we can continue to wait for more? But we want to wait for the entire timeout period and then take all that are done.
# Actually, we can do:
end_time = time.time() + self.timeout
updates = []
while time.time() < end_time and futures:
done, not_done = wait(futures, timeout=max(0, end_time - time.time()), return_when=FIRST_COMPLETED)
for future in done:
try:
update, num_samples = future.result()
updates.append((client_map[future], update, num_samples))
except Exception as e:
# dropout
pass
# Update the list of futures to the not_done ones?
futures = list(not_done)
# Then, after the while loop, we have collected all updates that completed within the timeout.
But note: the wait function with FIRST_COMPLETED will return as soon as at least one future completes. Then we remove that future and wait again? This is a way to continuously collect completed futures until the timeout.
However, we are in a loop and we are waiting multiple times. This might be acceptable.
But let's simplify: we are going to assume that we have a fixed timeout for the entire round and we are willing to wait for that timeout and then take any update that arrives by then. But we don't want to block on a single slow client.
Alternatively, we can set a timeout for each client task? But then we would have to run each client in a separate thread and set a timeout for that thread? We can't do that easily.
Given the complexity of asynchronous handling, and since this is a design question, let's assume we have a helper function that runs the client training with a timeout and returns None if timeout.
We can do:
def train_with_timeout(client, global_weights, timeout):
# run client.train in a separate thread and wait for timeout
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(client.train, global_weights)
try:
return future.result(timeout=timeout)
except concurrent.futures.TimeoutError:
return None
Then, for each client in the cohort, we can call this function with the same timeout? But that would be sequential? We want to run them in parallel.
So let's do:
We'll create a thread for each client, and then wait for all threads to finish or for the round timeout.
But note: if we set a timeout for each thread, then the total time might be more than the round timeout? Because if we have 10 clients and each has a 10-second timeout, and we run them in parallel, then the round might take 10 seconds? But if one client takes 2 seconds and another 12, then we wait 12?
Actually, we want to set a round timeout, so we start all clients at the same time and then wait for the round timeout. We can do:
start_time = time.time()
updates = []
with ThreadPoolExecutor(max_workers=len(cohort)) as executor:
futures = {}
for client in cohort:
if client.is_available:
future = executor.submit(client.train, global_weights)
futures[future] = client
while time.time() - start_time < self.timeout and futures:
# Wait for a short interval, say 0.1 seconds, to check for completed futures
done, not_done = wait(futures.keys(), timeout=0.1)
for future in done:
client = futures[future]
try:
update, num_samples = future.result()
updates.append((client.client_id, update, num_samples))
except Exception as e:
# dropout
client.set_availability(False)
finally:
del futures[future]
# Now, if there are any not_done futures, we cancel them? But we can't cancel running threads.
# We'll just leave them running? But we are going to proceed without them.
This is a busy wait, but it allows us to collect updates as they come and then break when the round timeout is reached.
Given the complexity, and since this is a design, let's simplify:
We'll assume that we have a fixed round timeout and we are willing to wait for that entire timeout. We'll use:
done, not_done = wait(futures, timeout=self.timeout)
and then process the done set. But note: the wait function with a timeout will wait for at least one future to complete or the timeout to expire. If the timeout expires and no future completed, then done is empty and not_done is all futures.
But if some futures complete before the timeout, then done will have those and not_done the rest. Then we can process the done and ignore the not_done (which are the ones that didn't complete in time).
So:
with ThreadPoolExecutor(max_workers=len(cohort)) as executor:
futures = [executor.submit(client.train, global_weights) for client in cohort if client.is_available]
done, not_done = wait(futures, timeout=self.timeout)
for future in done:
try:
update, num_samples = future.result()
updates.append((client_map[future], update, num_samples))
except Exception as e:
# This client dropped out or had an error
pass
# The not_done futures are the ones that didn't complete in time. We consider them dropped out.
But note: we don't have a mapping from future to client? We can create a dictionary:
future_to_client = {future: client for future, client in zip(futures, cohort) if client.is_available}
Then in the done loop:
for future in done:
client = future_to_client[future]
try:
update, num_samples = future.result()
updates.append((client.client_id, update, num_samples))
except Exception as e:
client.set_availability(False)
And then for the not_done futures, we can mark the clients as unavailable? But note: the not_done futures are still running? We can't cancel them, so we just ignore and mark the client as dropped out for this round.
However, we don't want to mark the client as permanently unavailable? Maybe we want to try again next round? So we might not set_availability(False) for timeout, but only for errors?
But in our design, we are simulating dropout by the client not responding in time. So we can mark the client as dropped out for this round, but we don't know if it's permanently down. So we might leave the availability as is?
Actually, in the next round, we will check availability again? We are not simulating network issues, so we might have a function that updates the availability list?
Let's assume that the available_clients list is updated by an external process (e.g., a device registry) and we just use that. So we don't change the client's availability in the server?
But then, if a client times out, we don't want to select it in the next round? Or do we?
It depends on the system. In a real system, if a client times out, it might be temporarily unavailable. We might want to avoid selecting it for a few rounds.
So we can have a mechanism to temporarily ban a client that drops out.
Given the complexity, let's keep it simple: we'll record the dropout and adjust the cohort selection strategy to avoid clients that have a high dropout rate.
We'll add to the client:
self.dropout_count = 0
self.total_rounds = 0
And when a client drops out (either by exception or by timeout), we increment dropout_count and total_rounds.
Then in the cohort selection, we can avoid clients with high dropout rate.
But for now, let's stick to random selection and just record the dropout.
We'll adjust the server to update the client's dropout_count and total_rounds when a dropout occurs.
However, note: in the above, we are only marking the client as unavailable when an exception occurs? For timeout, we are not marking?
Let's change: in the wait approach, the not_done futures are the ones that didn't complete in time. We should mark those clients as having dropped out due to timeout.
But note: the wait function returns two sets: done and not_done. The not_done are the futures that are still running? Actually, they are the ones that didn't complete within the timeout. So we can consider them as timed out.
So:
for future in done:
... process ...
for future in not_done:
client = future_to_client[future]
client.set_availability(False) # or mark as timed out?
But again, we might not want to set availability to False permanently? We might want to have a temporary ban?
Let's change the client to have:
self.temp_banned_until = None # if not None, then until when the client is banned
And then in the server, when we select cohort, we skip clients that are currently banned.
But for simplicity, let's just increment the dropout count and then in the selection, we can avoid clients with a dropout rate above a threshold.
So:
class Client:
def __init__(self, ...):
...
self.dropout_count = 0
self.total_rounds = 0
def mark_dropout(self):
self.dropout_count += 1
self.total_rounds += 1
def get_dropout_rate(self):
if self.total_rounds == 0:
return 0
return self.dropout_count / self.total_rounds
Then in the server's select_cohort, we can avoid clients with dropout_rate > threshold.
But note: we also want to avoid clients that have invalid updates? We can have a similar metric for invalid updates.
Given the time, let's stick to dropout.
Now, the update_validator and aggregator:
class UpdateValidator:
def validate(self, update, global_weights):
# Example: check the norm of the update
norm = np.linalg.norm(update)
if norm > threshold:
return False
return True
class Aggregator:
def aggregate(self, updates, global_weights):
# updates is a list of (update, num_samples)
# We do weighted average by num_samples
total_samples = sum(num_samples for _, num_samples in updates)
weighted_updates = [update * (num_samples / total_samples) for update, num_samples in updates]
new_weights = global_weights + sum(weighted_updates)
return new_weights
But note: the update is the difference between the local model and the global model? In FedAvg, the client sends the model update (delta) and the server aggregates the deltas weighted by the number of samples.
Actually, in the client, we return local_model_weights - global_weights? Then the server does:
new_weights = global_weights + (weighted sum of deltas)
So the above is correct.
However, note: the update_validator should check the delta? Or the new model? We are checking the delta.
Now, let's put it all together.
We'll design the server's run_round with the following steps:
1. Select cohort (using available_clients and possibly excluding high dropout clients)
2. For each client in cohort, if client.is_available (and not banned) then submit training task.
3. Wait for the tasks with a round timeout, and collect the completed ones.
4. For each completed task, if it returned without exception, then we have an update. Otherwise, mark the client as dropped out (increment dropout_count).
5. Validate each update. If valid, add to valid_updates. Otherwise, mark the client as having an invalid update? (maybe we don't want to select it again? we can have an invalid update count)
6. Aggregate the valid updates to get new global model.
We'll adjust the client to have:
- is_available: this is set by an external process (e.g., device registry). We might not change it in the server?
But we are simulating, so we can set it randomly?
Alternatively, we can have the server update the client's availability based on the round outcome?
Let's decide: the server does not change the client's availability. The availability is set by an external registry. But the server can record the dropout and invalid update counts and use that for cohort selection.
So in the server, when we select the cohort, we might exclude clients that have a high dropout rate or high invalid update rate.
We'll adjust the client to have:
self.stats = {
'dropout': 0,
'invalid_update': 0,
'total_participated': 0
}
And when a client drops out, we increment stats['dropout'] and stats['total_participated']? Actually, we increment total_participated when we select the client?
We want the rate: dropout_rate = dropout / total_participated.
So when we select a client for a round, we increment total_participated? But note: we might select a client and then it drops out, so we increment both?
Let's do:
In the server, when we select a client for the cohort, we increment the client's total_participated.
Then, if the client drops out (timeout or exception), we increment dropout.
If the client sends an update that fails validation, we increment invalid_update.
Then the server can avoid clients with high dropout_rate or high invalid_update_rate.
So:
class Client:
def __init__(self, ...):
...
self.stats = {
'total_participated': 0,
'dropout': 0,
'invalid_update': 0
}
def participate(self):
self.stats['total_participated'] += 1
def mark_dropout(self):
self.stats['dropout'] += 1
def mark_invalid_update(self):
self.stats['invalid_update'] += 1
def get_dropout_rate(self):
if self.stats['total_participated'] == 0:
return 0
return self.stats['dropout'] / self.stats['total_participated']
def get_invalid_update_rate(self):
if self.stats['total_participated'] == 0:
return 0
return self.stats['invalid_update'] / self.stats['total_participated']
Then in the server's select_cohort, we can filter out clients with dropout_rate > max_dropout_rate or invalid_update_rate > max_invalid_rate.
But note: we are selecting from available_clients. The availability is set by an external registry. So we have two filters:
- available (by registry)
- not having high dropout/invalid rate (by our own stats)
So:
def select_cohort(self):
# First, filter by availability and by stats
candidate_clients = [c for c in self.available_clients
if c.get_dropout_rate() <= self.max_dropout_rate
and c.get_invalid_update_rate() <= self.max_invalid_rate]
# Then randomly select cohort_size from candidate_clients
if len(candidate_clients) < self.cohort_size:
cohort = candidate_clients
else:
cohort = random.sample(candidate_clients, self.cohort_size)
# Increment the total_participated for each client in the cohort
for client in cohort:
client.participate()
return cohort
But note: we are incrementing total_participated even if the client drops out? Actually, we increment when we select the client, because we are counting participation in the round (being selected). Then if the client drops out, we increment dropout. So the dropout rate is the proportion of selected rounds in which the client dropped out.
This seems reasonable.
Now, what about the update_validator? We might want to adjust the validator based on the updates we have received? For example, we might set a threshold on the norm of the updates based on the median of the received updates?
But let's keep the validator simple and fixed.
Given the complexity of the design and the fact that we are writing code for a design, we'll write the server with the above logic, but note that the wait mechanism is not trivial.
Alternatively, we can use a simpler approach: we assume that the server sends the model to the clients and then waits for exactly cohort_size updates or until self.timeout, whichever comes first. But then we might wait for the slowest client?
We want to avoid waiting for stragglers, so we set a timeout and then aggregate the updates we have.
Given the time, let's write the server with the following wait mechanism:
We'll use a ThreadPoolExecutor to submit all client training tasks.
Then we'll use `wait` with a timeout for the entire set of futures, and then process the ones that are done.
Code for run_round:
def run_round(self):
cohort = self.select_cohort()
global_weights = self.global_model.get_weights()
# Map futures to clients
future_to_client = {}
with ThreadPoolExecutor(max_workers=len(cohort)) as executor:
for client in cohort:
future = executor.submit(client.train, global_weights)
future_to_client[future] = client
# Wait for the futures to complete with a timeout
done, not_done = wait(future_to_client.keys(), timeout=self.timeout)
updates = []
for future in done:
client = future_to_client[future]
try:
update, num_samples = future.result()
updates.append((client.client_id, update, num_samples))
except Exception as e:
# This client had an error (not timeout, because timeout futures are in not_done)
client.mark_dropout()
print(f"Client {client.client_id} failed with exception: {e}")
# The not_done futures are the ones that timed out
for future in not_done:
client = future_to_client[future]
client.mark_dropout()
print(f"Client {client.client_id} timed out.")
# Now validate updates
valid_updates = []
for client_id, update, num_samples in updates:
if self.update_validator.validate(update, global_weights):
valid_updates.append((update, num_samples))
else:
# Find the client by client_id? We have the client_id, but we need to mark the client.
# We can store a mapping from client_id to client? Or we can pass the client along?
# Let's change: we stored (client_id, update, num_samples). We need the client object to mark invalid.
# So we should store (client, update, num_samples) instead.
Let's change: in the done loop, we store (client, update, num_samples). Then:
for client, update, num_samples in updates:
if self.update_validator.validate(update, global_weights):
valid_updates.append((update, num_samples))
else:
client.mark_invalid_update()
Then aggregate.
But wait, we already marked the client as dropout for exceptions and timeouts. Now we are marking invalid_update for validation failure.
So:
For each client in the cohort:
- If the client's future raises an exception -> dropout.
- If the client's future times out -> dropout.
- If the client's future completes but the update fails validation -> invalid_update.
Then we aggregate only the valid updates.
Now, what about the aggregator? We have a list of (update, num_samples) for valid updates.
We'll assume the aggregator has a method aggregate that takes the list and the global_weights and returns new_weights.
Finally, we set the global model to the new_weights.
We also need to handle the case when there are no valid updates? Then we skip aggregation.
Let's code accordingly.
We'll also note that the client.train method should return (update, num_samples). The update is the difference between the local model and the global_weights?
Actually, in the client.train, we set the local model to global_weights, then train, then compute the update as:
update = local_model.get_weights() - global_weights
and the number of samples is the number of local training samples.
Now, let's write the classes accordingly.
We'll also need a way to get the global model's weights and set them. We assume the model has get_weights and set_weights.
We'll design:
We need to define the DefaultUpdateValidator and FedAvgAggregator.
class DefaultUpdateValidator:
def __init__(self, max_norm=10.0):
self.max_norm = max_norm
def validate(self, update, global_weights):
# update is a list of numpy arrays (the weight differences)
total_norm = 0
for u in update:
total_norm += np.linalg.norm(u) ** 2
total_norm = np.sqrt(total_norm)
return total_norm <= self.max_norm
class FedAvgAggregator:
def aggregate(self, updates, global_weights):
# updates: list of (update, num_samples)
total_samples = sum(num_samples for _, num_samples in updates)
if total_samples == 0:
return global_weights
# Compute weighted average of updates
weighted_updates = []
for update, num_samples in updates:
weight = num_samples / total_samples
weighted_update = [u * weight for u in update]
weighted_updates.append(weighted_update)
# Sum the weighted updates
sum_weighted_updates = [sum(u) for u in zip(*weighted_updates)]
new_weights = [global + sum_update for global, sum_update in zip(global_weights, sum_weighted_updates)]
return new_weights
Note: the above aggregator assumes that the updates are in the same order as global_weights and that they are numpy arrays.
This is a basic design. We can extend it by:
- Having more sophisticated cohort selection (e.g., based on client performance, data heterogeneity, etc.)
- Having a more robust aggregator (e.g., using median-based aggregation to handle malicious updates)
- Adjusting the timeout based on past round completion times.
- Having a mechanism to temporarily ban clients that drop out or send invalid updates.
But for the purpose of this design, we have:
- Cohort selection with filtering based on dropout and invalid update rates.
- Handling device dropout by timeout and exception.
- Update validation by norm threshold.
We assume that the available_clients list is updated externally (e.g., by a device registry that pings clients). We don't model that in the server.
We also assume that the client's data and model are set appropriately.
This is a simulation, so we can test with mock clients and data.
Let me write the code accordingly.
However, note: the wait function from concurrent.futures waits for at least one future to complete or until the timeout. We are using it to wait for the entire set? Actually, we are passing the set of all futures and a timeout. It returns two sets: the ones that completed and the ones that didn't. So we are waiting for the entire set? But if one future completes quickly, then we get it in done and the rest in not_done?
Actually, the wait function with a timeout will return when either at least one future completes or the timeout expires. So if we have 10 clients and one completes in 1 second, then after 1 second we get done with one future and not_done with 9. But we are not waiting for the others?
This is not what we want. We want to wait for the entire timeout period and then get all the futures that completed within that period.
So we need to call wait repeatedly until the timeout expires?
Alternatively, we can use as_completed and break after the timeout?
Let me change the approach:
We want to wait for a maximum of `self.timeout` seconds and collect all futures that complete within that time.
We can do:
start = time.time()
done = set()
not_done = set(future_to_client.keys())
while not_done and time.time() - start < self.timeout:
# Wait for a short time, say 0.1 seconds, to check for completed futures
done_now, not_done = wait(not_done, timeout=0.1)
done |= done_now
# Then, the `done` set contains all futures that completed within the timeout.
But note: the `wait` function with a timeout of 0.1 will wait at most 0.1 seconds and then return the done and not_done sets. So we are effectively polling every 0.1 seconds.
This is acceptable.
Let's adjust the run_round:
with ThreadPoolExecutor(max_workers=len(cohort)) as executor:
futures = {}
for client in cohort:
future = executor.submit(client.train, global_weights)
futures[future] = client
start_time = time.time()
done = set()
not_done = set(futures.keys())
while not_done and time.time() - start_time < self.timeout:
done_now, not_done = wait(not_done, timeout=0.1)
done |= done_now
# Now, `done` contains all futures that completed within the timeout.
# The remaining `not_done` are the ones that didn't complete in time.
for future in done:
... same as before ...
for future in not_done:
... mark as timeout ...
This way, we wait for the entire timeout period and collect all the futures that complete in the meantime.
Let's code accordingly.
However, note: the wait function returns two sets: the done set and the not_done set. The not_done set returned by wait is the set of futures that were not done at the time of the call. So we are updating not_done to be the ones that are still running after the 0.1 seconds.
This loop will break when either there are no more not_done futures (all completed) or the timeout expired.
Then we process the done futures and mark the not_done as timed out.
This seems reasonable.
Let's code the server with this wait mechanism.
We'll also note that the client.train might take a long time, but we are only waiting for the timeout.
Now, let's write the code accordingly.
We'll assume we have the necessary imports.
Due to the complexity and length, I'll write the code in the following order:
imports
class Client
class DefaultUpdateValidator
class FedAvgAggregator
class ControlTower
We'll also note that the model's get_weights and set_weights are assumed to return and take a list of numpy arrays.
Let's code. I'll design a comprehensive federated learning control tower system with robust cohort selection, dropout handling, and update validation mechanisms.
# Typical production configuration
config = {
'cohort_selector': {
'target_cohort_size': 100,
'max_dropout_tolerance': 0.2,
'diversity_weight': 0.4,
'reliability_weight': 0.4,
'latency_weight': 0.2
},
'dropout_handler': {
'heartbeat_timeout': 30.0,
'max_consecutive_dropouts': 3,
'cooldown_period': 600.0
},
'update_validator': {
'max_norm_threshold': 10.0,
'min_norm_threshold': 1e-6,
'consistency_window': 5,
'historical_window': 20
},
'aggregator': {
'method': 'trimmed_mean',
'trim_ratio': 0.2,
'min_valid_updates': 10
}
}
CohortSelector for domain-specific selectionUpdateValidatorThis implementation provides a production-ready foundation that can handle real-world challenges in federated learning deployments including heterogeneous devices, unreliable networks, and potential adversarial participants.
def select_cohort(self):
# randomly select cohort_size clients from available_clients
# but we might want to use a more sophisticated strategy
import random
if len(self.available_clients) < self.cohort_size:
cohort = self.available_clients
else:
cohort = random.sample(self.available_clients, self.cohort_size)
return cohort
def run_round(self):
cohort = self.select_cohort()
global_weights = self.global_model.get_weights()
# We'll simulate sending the model and receiving updates asynchronously?
# For simplicity, we'll do it in a loop with a timeout per client?
# But note: we are in a single thread and we want to wait for multiple clients.
# Instead, we can use a thread pool to send the model and train on each client, and then wait for the results with a timeout.
from concurrent.futures import ThreadPoolExecutor, as_completed
updates = []
with ThreadPoolExecutor(max_workers=len(cohort)) as executor:
# Submit training tasks for each client in the cohort
future_to_client = {}
for client in cohort:
if client.is_available:
future = executor.submit(client.train, global_weights)
future_to_client[future] = client
else:
# client is marked as dropped out, skip
pass
# Wait for the tasks to complete, with a timeout for each task?
# Actually, we set a timeout for the entire round? We can wait for the first `cohort_size` tasks?
# But we have a fixed cohort. We want to wait for all the tasks we submitted, but if one takes too long, we don't want to wait forever.
# We'll wait for the futures with a timeout per future? Actually, we can set a timeout for the entire round and then take whatever is done.
# Let's wait for the futures with the round timeout? But note: the timeout is for the entire round?
# Alternatively, we can wait for each future with a timeout of `self.timeout` and then if not done, cancel it.
# However, note that the client.train might take a long time. We want to give each client at most `self.timeout` seconds.
# We'll do:
for future in as_completed(future_to_client, timeout=self.timeout):
client = future_to_client[future]
try:
update, num_samples = future.result()
updates.append((client.client_id, update, num_samples))
except Exception as e:
# This client dropped out (or had an error)
print(f"Client {client.client_id} dropped out: {e}")
# We can mark the client as unavailable for future rounds if needed?
client.set_availability(False)
# Now, what about the futures that didn't complete?
# We can cancel them? But the threads are already running. We can't cancel a running thread in Python.
# So we just ignore them and consider those clients dropped out.
# Now we have a list of updates (from clients that responded in time)
# Validate each update
valid_updates = []
for client_id, update, num_samples in updates:
if self.update_validator.validate(update, global_weights):
valid_updates.append((update, num_samples))
else:
print(f"Update from client {client_id} failed validation.")
# Aggregate the valid updates
if valid_updates:
new_weights = self.aggregator.aggregate(valid_updates, global_weights)
self.global_model.set_weights(new_weights)
else:
print("No valid updates received. Global model unchanged.")
# Optionally, update the server's knowledge about clients (e.g., record dropout, validation failures)
class Client:
def __init__(self, client_id, data, model_fn):
self.client_id = client_id
self.data = data
self.model = model_fn()
self.stats = {'total_participated':0, 'dropout':0, 'invalid_update':0}
def participate(self):
self.stats['total_participated'] += 1
def mark_dropout(self):
self.stats['dropout'] += 1
def mark_invalid_update(self):
self.stats['invalid_update'] += 1
def get_dropout_rate(self):
if self.stats['total_participated'] == 0:
return 0
return self.stats['dropout'] / self.stats['total_participated']
def get_invalid_update_rate(self):
if self.stats['total_participated'] == 0:
return 0
return self.stats['invalid_update'] / self.stats['total_participated']
def train(self, global_weights, epochs=1, batch_size=32):
# Set local model to global_weights
self.model.set_weights(global_weights)
# Train on local data
# ... training code ...
# After training, get the new weights
local_weights = self.model.get_weights()
# Compute update
update = [local - global for local, global in zip(local_weights, global_weights)]
num_samples = len(self.data) # assuming data is a dataset with __len__
return update, num_samples
class ControlTower:
def __init__(self, global_model, available_clients, cohort_size, timeout,
max_dropout_rate=0.5, max_invalid_rate=0.5,
update_validator=None, aggregator=None):
self.global_model = global_model
self.available_clients = available_clients
self.cohort_size = cohort_size
self.timeout = timeout
self.max_dropout_rate = max_dropout_rate
self.max_invalid_rate = max_invalid_rate
self.update_validator = update_validator or DefaultUpdateValidator()
self.aggregator = aggregator or FedAvgAggregator()
def select_cohort(self):
# Filter clients by availability and by stats
candidate_clients = [c for c in self.available_clients
if c.get_dropout_rate() <= self.max_dropout_rate
and c.get_invalid_update_rate() <= self.max_invalid_rate]
if len(candidate_clients) < self.cohort_size:
cohort = candidate_clients
else:
cohort = random.sample(candidate_clients, self.cohort_size)
for client in cohort:
client.participate()
return cohort
def run_round(self):
cohort = self.select_cohort()
if not cohort:
print("No clients available for this round.")
return
global_weights = self.global_model.get_weights()
future_to_client = {}
with ThreadPoolExecutor(max_workers=len(cohort)) as executor:
for client in cohort:
future = executor.submit(client.train, global_weights)
future_to_client[future] = client
done, not_done = wait(future_to_client.keys(), timeout=self.timeout)
updates = [] # list of (client, update, num_samples)
for future in done:
client = future_to_client[future]
try:
update, num_samples = future.result()
updates.append((client, update, num_samples))
except Exception as e:
client.mark_dropout()
print(f"Client {client.client_id} failed: {e}")
for future in not_done:
client = future_to_client[future]
client.mark_dropout()
print(f"Client {client.client_id} timed out.")
valid_updates = [] # list of (update, num_samples)
for client, update, num_samples in updates:
if self.update_validator.validate(update, global_weights):
valid_updates.append((update, num_samples))
else:
client.mark_invalid_update()
print(f"Client {client.client_id} provided an invalid update.")
if valid_updates:
new_weights = self.aggregator.aggregate(valid_updates, global_weights)
self.global_model.set_weights(new_weights)
else:
print("No valid updates to aggregate.")
import asyncio
import time
import numpy as np
from typing import List, Dict, Tuple, Optional, Any
from dataclasses import dataclass, field
from enum import Enum
from collections import defaultdict, deque
import hashlib
import json
# ============== Enumerations ==============
class ClientStatus(Enum):
AVAILABLE = "available"
TRAINING = "training"
DROPPED = "dropped"
FAILED = "failed"
VALIDATED = "validated"
class ValidationResult(Enum):
PASS = "pass"
FAIL_NORM = "fail_norm"
FAIL_CONSISTENCY = "fail_consistency"
FAIL_HISTORICAL = "fail_historical"
FAIL_TIMEOUT = "fail_timeout"
# ============== Data Structures ==============
@dataclass
class ClientMetrics:
"""Track client-specific metrics for intelligent selection"""
client_id: str
total_rounds: int = 0
successful_rounds: int = 0
dropout_count: int = 0
last_seen: float = field(default_factory=time.time)
avg_latency: float = 0.0
update_quality_score: float = 1.0 # 0-1 scale
data_distribution_hash: Optional[str] = None
hardware_profile: Dict[str, Any] = field(default_factory=dict)
@property
def dropout_rate(self) -> float:
return self.dropout_count / max(1, self.total_rounds)
@property
def reliability_score(self) -> float:
if self.total_rounds == 0:
return 0.5
success_rate = self.successful_rounds / self.total_rounds
return 0.7 * success_rate + 0.3 * (1 - self.dropout_rate)
@dataclass
class FederatedRound:
"""Track metadata for each federated learning round"""
round_id: int
cohort: List[str]
start_time: float
end_time: Optional[float] = None
expected_updates: int = 0
received_updates: int = 0
valid_updates: int = 0
dropout_clients: List[str] = field(default_factory=list)
validation_failures: Dict[str, ValidationResult] = field(default_factory=dict)
aggregated_model_hash: Optional[str] = None
# ============== Core Components ==============
class CohortSelector:
"""Intelligent cohort selection based on multiple factors"""
def __init__(self,
target_cohort_size: int = 50,
max_dropout_tolerance: float = 0.3,
diversity_weight: float = 0.4,
reliability_weight: float = 0.4,
latency_weight: float = 0.2):
self.target_cohort_size = target_cohort_size
self.max_dropout_tolerance = max_dropout_tolerance
self.weights = {
'diversity': diversity_weight,
'reliability': reliability_weight,
'latency': latency_weight
}
self.client_metrics: Dict[str, ClientMetrics] = {}
def update_metrics(self, client_id: str, **kwargs):
"""Update client metrics"""
if client_id not in self.client_metrics:
self.client_metrics[client_id] = ClientMetrics(client_id=client_id)
metrics = self.client_metrics[client_id]
for key, value in kwargs.items():
if hasattr(metrics, key):
setattr(metrics, key, value)
def select_cohort(self,
available_clients: List[str],
round_id: int,
previous_round: Optional[FederatedRound] = None) -> List[str]:
"""
Select optimal cohort using multi-criteria decision making
Strategy:
1. Filter out clients with high dropout history (> tolerance)
2. Score remaining clients based on reliability, latency, and diversity
3. Select top-k clients with maximum diversity
"""
# Step 1: Filter based on reliability
candidate_clients = []
for client_id in available_clients:
metrics = self.client_metrics.get(client_id, ClientMetrics(client_id))
if metrics.dropout_rate <= self.max_dropout_tolerance:
candidate_clients.append(client_id)
if len(candidate_clients) < self.target_cohort_size // 2:
# Fallback: include more clients if not enough reliable ones
candidate_clients = available_clients[:self.target_cohort_size]
# Step 2: Score clients
client_scores = {}
for client_id in candidate_clients:
metrics = self.client_metrics.get(client_id, ClientMetrics(client_id))
score = (
self.weights['reliability'] * metrics.reliability_score +
self.weights['latency'] * (1 / max(1, metrics.avg_latency)) +
self.weights['diversity'] * self._calculate_diversity_score(client_id, previous_round)
)
client_scores[client_id] = score
# Step 3: Select top-k with diversity constraint
sorted_clients = sorted(client_scores.items(), key=lambda x: x[1], reverse=True)
selected = []
selected_hashes = set()
for client_id, _ in sorted_clients:
if len(selected) >= self.target_cohort_size:
break
metrics = self.client_metrics.get(client_id)
if metrics and metrics.data_distribution_hash:
if metrics.data_distribution_hash not in selected_hashes:
selected.append(client_id)
selected_hashes.add(metrics.data_distribution_hash)
else:
selected.append(client_id)
# Update metrics for selected clients
for client_id in selected:
self.update_metrics(client_id, total_rounds=self.client_metrics[client_id].total_rounds + 1)
return selected
def _calculate_diversity_score(self, client_id: str,
previous_round: Optional[FederatedRound]) -> float:
"""Calculate diversity contribution of a client"""
if not previous_round or not previous_round.cohort:
return 1.0
current_hash = self.client_metrics[client_id].data_distribution_hash
if not current_hash:
return 0.5
# Check uniqueness compared to previous cohort
unique_count = 0
for prev_client in previous_round.cohort:
prev_metrics = self.client_metrics.get(prev_client)
if prev_metrics and prev_metrics.data_distribution_hash:
if prev_metrics.data_distribution_hash != current_hash:
unique_count += 1
return unique_count / len(previous_round.cohort)
class DropoutHandler:
"""Manage device dropout detection and recovery"""
def __init__(self,
heartbeat_timeout: float = 30.0,
max_consecutive_dropouts: int = 3,
cooldown_period: float = 300.0):
self.heartbeat_timeout = heartbeat_timeout
self.max_consecutive_dropouts = max_consecutive_dropouts
self.cooldown_period = cooldown_period
self.client_last_heartbeat: Dict[str, float] = {}
self.consecutive_dropouts: Dict[str, int] = defaultdict(int)
self.cooldown_until: Dict[str, float] = {}
async def monitor_heartbeat(self, client_id: str):
"""Monitor client heartbeat"""
current_time = time.time()
self.client_last_heartbeat[client_id] = current_time
def check_dropout(self, client_id: str, current_time: float) -> bool:
"""Check if client has dropped out"""
# Check cooldown
if client_id in self.cooldown_until:
if current_time < self.cooldown_until[client_id]:
return True
else:
del self.cooldown_until[client_id]
# Check heartbeat timeout
last_heartbeat = self.client_last_heartbeat.get(client_id, 0)
if current_time - last_heartbeat > self.heartbeat_timeout:
self.consecutive_dropouts[client_id] += 1
if self.consecutive_dropouts[client_id] >= self.max_consecutive_dropouts:
# Put client in cooldown
self.cooldown_until[client_id] = current_time + self.cooldown_period
return True
return True
# Reset consecutive dropouts on successful heartbeat
self.consecutive_dropouts[client_id] = 0
return False
def get_dropout_statistics(self) -> Dict[str, Any]:
"""Get current dropout statistics"""
total_clients = len(self.client_last_heartbeat)
dropped_clients = sum(1 for c in self.client_last_heartbeat
if self.check_dropout(c, time.time()))
return {
'total_clients': total_clients,
'dropped_clients': dropped_clients,
'dropout_rate': dropped_clients / max(1, total_clients),
'cooldown_clients': len(self.cooldown_until)
}
class UpdateValidator:
"""Multi-layered validation for client updates"""
def __init__(self,
max_norm_threshold: float = 10.0,
min_norm_threshold: float = 1e-6,
consistency_window: int = 5,
historical_window: int = 10):
self.max_norm_threshold = max_norm_threshold
self.min_norm_threshold = min_norm_threshold
self.consistency_window = consistency_window
self.historical_window = historical_window
# Store historical updates for consistency checking
self.client_update_history: Dict[str, deque] = defaultdict(
lambda: deque(maxlen=historical_window)
)
self.global_model_history: deque = deque(maxlen=historical_window)
def validate_update(self,
client_id: str,
update: np.ndarray,
global_model: np.ndarray,
client_params: Dict[str, Any]) -> Tuple[bool, ValidationResult, Dict[str, Any]]:
"""
Validate client update using multiple checks
Returns:
(is_valid, failure_reason, metadata)
"""
metadata = {}
# 1. Norm checks
update_norm = np.linalg.norm(update)
if update_norm < self.min_norm_threshold:
return False, ValidationResult.FAIL_NORM, {'norm': update_norm, 'reason': 'too_small'}
if update_norm > self.max_norm_threshold:
return False, ValidationResult.FAIL_NORM, {'norm': update_norm, 'reason': 'too_large'}
metadata['update_norm'] = float(update_norm)
# 2. Consistency with historical updates
if self._check_consistency(client_id, update):
return False, ValidationResult.FAIL_CONSISTENCY, metadata
# 3. Historical pattern check
if self._check_historical_pattern(client_id, update):
return False, ValidationResult.FAIL_HISTORICAL, metadata
# 4. Parameter sanity checks
if not self._check_parameters(client_params):
return False, ValidationResult.FAIL_NORM, {'reason': 'invalid_parameters'}
# Store update for future consistency checks
self.client_update_history[client_id].append({
'update': update.copy(),
'norm': update_norm,
'timestamp': time.time()
})
return True, ValidationResult.PASS, metadata
def _check_consistency(self, client_id: str, new_update: np.ndarray) -> bool:
"""Check if update is consistent with client's recent updates"""
history = self.client_update_history[client_id]
if len(history) < 2:
return False
# Calculate cosine similarity with recent updates
recent_updates = [h['update'] for h in list(history)[-self.consistency_window:]]
for old_update in recent_updates:
similarity = np.dot(new_update.flatten(), old_update.flatten()) / (
np.linalg.norm(new_update) * np.linalg.norm(old_update) + 1e-8
)
if similarity > 0.99: # Too similar, possible replay attack
return True
return False
def _check_historical_pattern(self, client_id: str, new_update: np.ndarray) -> bool:
"""Check for suspicious patterns in client's update history"""
history = self.client_update_history[client_id]
if len(history) < 3:
return False
# Check for oscillating patterns (possible adversarial)
recent_norms = [h['norm'] for h in list(history)[-3:]]
if len(set(recent_norms)) == 1: # Exactly same norm repeatedly
return True
# Check for extreme variance
norm_variance = np.var(recent_norms)
if norm_variance > 100: # Arbitrary threshold
return True
return False
def _check_parameters(self, params: Dict[str, Any]) -> bool:
"""Validate client training parameters"""
required_params = ['learning_rate', 'batch_size', 'local_epochs']
for param in required_params:
if param not in params:
return False
if not isinstance(params[param], (int, float)) or params[param] <= 0:
return False
return True
def calculate_update_hash(self, update: np.ndarray) -> str:
"""Create hash of update for integrity verification"""
return hashlib.sha256(update.tobytes()).hexdigest()[:16]
class RobustAggregator:
"""Robust aggregation with outlier detection"""
def __init__(self,
method: str = 'median',
trim_ratio: float = 0.2,
min_valid_updates: int = 3):
self.method = method
self.trim_ratio = trim_ratio
self.min_valid_updates = min_valid_updates
def aggregate(self,
updates: List[Tuple[np.ndarray, int]],
global_model: np.ndarray,
weights: Optional[List[float]] = None) -> np.ndarray:
"""
Aggregate updates using robust method
Args:
updates: List of (update, num_samples) tuples
global_model: Current global model
weights: Optional client weights (defaults to num_samples)
Returns:
New global model weights
"""
if len(updates) < self.min_valid_updates:
raise ValueError(f"Need at least {self.min_valid_updates} valid updates")
# Separate updates and sample counts
update_arrays = [u[0] for u in updates]
sample_counts = np.array([u[1] for u in updates])
if weights is None:
weights = sample_counts / sample_counts.sum()
else:
weights = np.array(weights)
weights = weights / weights.sum()
# Convert to parameter-wise arrays
param_updates = []
for i in range(len(update_arrays[0])):
layer_updates = np.array([u[i] for u in update_arrays])
param_updates.append(layer_updates)
# Apply robust aggregation per layer
new_params = []
for layer_idx, layer_updates in enumerate(param_updates):
if self.method == 'median':
# Coordinate-wise median
median_update = np.median(layer_updates, axis=0)
weighted_update = np.zeros_like(median_update)
for i, update in enumerate(layer_updates):
weighted_update += update * weights[i]
new_params.append(global_model[layer_idx] + weighted_update)
elif self.method == 'trimmed_mean':
# Trimmed mean (remove top/bottom trim_ratio)
n = len(layer_updates)
k = int(n * self.trim_ratio)
if k > 0:
sorted_updates = np.sort(layer_updates, axis=0)
trimmed = sorted_updates[k:-k] if k > 0 else sorted_updates
trimmed_mean = np.mean(trimmed, axis=0)
else:
trimmed_mean = np.mean(layer_updates, axis=0)
weighted_update = np.zeros_like(trimmed_mean)
for i, update in enumerate(layer_updates):
weighted_update += update * weights[i]
new_params.append(global_model[layer_idx] + weighted_update)
elif self.method == 'klife':
# K-overlap resilient aggregation (simplified)
# Calculate median and MAD (Median Absolute Deviation)
median = np.median(layer_updates, axis=0)
mad = np.median(np.abs(layer_updates - median), axis=0)
mad = np.where(mad == 0, 1e-8, mad) # Avoid division by zero
# Compute z-scores
z_scores = np.abs(layer_updates - median) / (1.4826 * mad + 1e-8)
# Weight updates by inverse of z-score (robust weighting)
robust_weights = 1 / (1 + z_scores)
robust_weights = robust_weights / robust_weights.sum(axis=0, keepdims=True)
weighted_update = np.sum(layer_updates * robust_weights, axis=0)
new_params.append(global_model[layer_idx] + weighted_update)
return new_params
# ============== Main Control Tower ==============
class FederatedLearningControlTower:
"""
Central control tower managing the entire federated learning process
"""
def __init__(self,
initial_model: np.ndarray,
cohort_selector: CohortSelector,
dropout_handler: DropoutHandler,
update_validator: UpdateValidator,
aggregator: RobustAggregator,
round_timeout: float = 300.0,
min_cohort_size: int = 5,
max_rounds: int = 1000):
self.global_model = initial_model
self.cohort_selector = cohort_selector
self.dropout_handler = dropout_handler
self.update_validator = update_validator
self.aggregator = aggregator
self.round_timeout = round_timeout
self.min_cohort_size = min_cohort_size
self.max_rounds = max_rounds
self.available_clients: List[str] = []
self.client_models: Dict[str, np.ndarray] = {}
self.client_status: Dict[str, ClientStatus] = {}
self.round_history: List[FederatedRound] = []
self.current_round: Optional[FederatedRound] = None
self.round_counter = 0
# Performance tracking
self.metrics = {
'total_rounds': 0,
'successful_rounds': 0,
'avg_round_time': 0.0,
'total_updates_received': 0,
'total_updates_validated': 0,
'dropout_rate': 0.0,
'aggregation_success_rate': 0.0
}
def register_client(self, client_id: str, hardware_profile: Dict[str, Any]):
"""Register a new client"""
self.available_clients.append(client_id)
self.client_status[client_id] = ClientStatus.AVAILABLE
self.cohort_selector.update_metrics(
client_id,
hardware_profile=hardware_profile
)
async def execute_round(self) -> FederatedRound:
"""Execute one federated learning round"""
self.round_counter += 1
if self.round_counter > self.max_rounds:
raise StopIteration("Maximum rounds reached")
round_id = self.round_counter
start_time = time.time()
# Step 1: Select cohort
previous_round = self.round_history[-1] if self.round_history else None
cohort = self.cohort_selector.select_cohort(
self.available_clients,
round_id,
previous_round
)
if len(cohort) < self.min_cohort_size:
print(f"Warning: Cohort size {len(cohort)} below minimum {self.min_cohort_size}")
current_round = FederatedRound(
round_id=round_id,
cohort=cohort,
start_time=start_time,
expected_updates=len(cohort)
)
self.current_round = current_round
print(f"Round {round_id}: Selected cohort of {len(cohort)} clients")
# Step 2: Distribute model and monitor
tasks = []
for client_id in cohort:
task = asyncio.create_task(
self._train_and_update(client_id, self.global_model)
)
tasks.append(task)
self.client_status[client_id] = ClientStatus.TRAINING
# Step 3: Wait for updates with timeout
try:
await asyncio.wait_for(
asyncio.gather(*tasks, return_exceptions=True),
timeout=self.round_timeout
)
except asyncio.TimeoutError:
print(f"Round {round_id}: Timeout reached")
# Step 4: Process results
await self._process_round_results(current_round)
# Step 5: Aggregate if enough valid updates
if current_round.valid_updates >= self.min_cohort_size:
try:
self._aggregate_updates(current_round)
self.metrics['aggregation_success_rate'] += 1
current_round.end_time = time.time()
except ValueError as e:
print(f"Round {round_id}: Aggregation failed - {e}")
else:
print(f"Round {round_id}: Insufficient valid updates ({current_round.valid_updates})")
# Update metrics
self._update_metrics(current_round)
self.round_history.append(current_round)
self.current_round = None
return current_round
async def _train_and_update(self, client_id: str, global_model: np.ndarray) -> Dict[str, Any]:
"""Simulate client training and update submission"""
try:
# Check for dropout
if self.dropout_handler.check_dropout(client_id, time.time()):
return {
'client_id': client_id,
'status': 'dropped',
'update': None,
'num_samples': 0,
'params': {}
}
# Send heartbeat
await self.dropout_handler.monitor_heartbeat(client_id)
# Simulate training (in real system, this would be async network call)
# Here we simulate with random delay and update generation
await asyncio.sleep(np.random.uniform(0.5, 5.0))
# Generate mock update (in reality, client would compute this)
update = np.random.normal(0, 0.01, global_model.shape)
num_samples = np.random.randint(100, 1000)
# Simulate occasional bad updates (for validation testing)
if np.random.random() < 0.1: # 10% chance of malicious update
update = np.random.normal(5.0, 1.0, global_model.shape) # Large update
return {
'client_id': client_id,
'status': 'success',
'update': update,
'num_samples': num_samples,
'params': {
'learning_rate': 0.01,
'batch_size': 32,
'local_epochs': 5
}
}
except Exception as e:
return {
'client_id': client_id,
'status': 'failed',
'error': str(e),
'update': None,
'num_samples': 0,
'params': {}
}
async def _process_round_results(self, round_obj: FederatedRound):
"""Process all client responses for the round"""
valid_updates = []
for client_id in round_obj.cohort:
# In real system, we'd have the actual result from the task
# For simulation, we'll generate based on status
status = self.client_status.get(client_id, ClientStatus.AVAILABLE)
if status == ClientStatus.DROPPED:
round_obj.dropout_clients.append(client_id)
self.cohort_selector.update_metrics(client_id, dropout_count=1)
elif status == ClientStatus.FAILED:
round_obj.validation_failures[client_id] = ValidationResult.FAIL_TIMEOUT
self.cohort_selector.update_metrics(client_id, dropout_count=1)
# In simulation, we'd collect actual results from tasks
# For demo, we'll simulate validation
self._simulate_validation_results(round_obj)
def _simulate_validation_results(self, round_obj: FederatedRound):
"""Simulate validation results for demonstration"""
# In real system, this would use actual client responses
for client_id in round_obj.cohort:
if client_id in round_obj.dropout_clients:
continue
# Simulate validation (random for demo)
if np.random.random() < 0.9: # 90% pass rate
round_obj.valid_updates += 1
self.client_status[client_id] = ClientStatus.VALIDATED
else:
failure_type = np.random.choice([
ValidationResult.FAIL_NORM,
ValidationResult.FAIL_CONSISTENCY,
ValidationResult.FAIL_HISTORICAL
])
round_obj.validation_failures[client_id] = failure_type
self.cohort_selector.update_metrics(
client_id,
invalid_update=self.client_metrics[client_id].stats.get('invalid_update', 0) + 1
)
def _aggregate_updates(self, round_obj: FederatedRound):
"""Aggregate validated updates"""
# In real system, collect actual validated updates
# For demo, we'll create mock valid updates
valid_clients = [
c for c in round_obj.cohort
if c not in round_obj.dropout_clients
and c not in round_obj.validation_failures
]
if len(valid_clients) < self.min_cohort_size:
raise ValueError(f"Only {len(valid_clients)} valid updates, need {self.min_cohort_size}")
# Create mock updates for aggregation
mock_updates = []
for client_id in valid_clients:
update = np.random.normal(0, 0.01, self.global_model.shape)
num_samples = np.random.randint(100, 1000)
mock_updates.append((update, num_samples))
# Aggregate
new_model = self.aggregator.aggregate(mock_updates, self.global_model)
self.global_model = new_model
# Calculate hash
round_obj.aggregated_model_hash = self.update_validator.calculate_update_hash(
new_model - self.global_model # This would be the delta
)
def _update_metrics(self, round_obj: FederatedRound):
"""Update global metrics"""
self.metrics['total_rounds'] += 1
if round_obj.valid_updates >= self.min_cohort_size:
self.metrics['successful_rounds'] += 1
if round_obj.end_time:
round_time = round_obj.end_time - round_obj.start_time
self.metrics['avg_round_time'] = (
(self.metrics['avg_round_time'] * (self.metrics['total_rounds'] - 1) + round_time) /
self.metrics['total_rounds']
)
self.metrics['total_updates_received'] += round_obj.received_updates
self.metrics['total_updates_validated'] += round_obj.valid_updates
# Calculate current dropout rate
dropout_stats = self.dropout_handler.get_dropout_statistics()
self.metrics['dropout_rate'] = dropout_stats['dropout_rate']
def get_system_status(self) -> Dict[str, Any]:
"""Get complete system status"""
return {
'global_metrics': self.metrics,
'current_round': self.current_round.__dict__ if self.current_round else None,
'dropout_stats': self.dropout_handler.get_dropout_statistics(),
'cohort_selector_stats': {
'registered_clients': len(self.available_clients),
'client_metrics': {
cid: metrics.__dict__
for cid, metrics in self.cohort_selector.client_metrics.items()
}
}
}
def save_checkpoint(self, path: str):
"""Save system state"""
checkpoint = {
'global_model': self.global_model.tolist(),
'round_counter': self.round_counter,
'metrics': self.metrics,
'client_metrics': {
cid: metrics.__dict__
for cid, metrics in self.cohort_selector.client_metrics.items()
}
}
with open(path, 'w') as f:
json.dump(checkpoint, f)
# ============== Usage Example ==============
async def example_usage():
"""Example usage of the federated learning control tower"""
# Initialize components
initial_model = np.random.randn(10, 10) # Example model
cohort_selector = CohortSelector(target_cohort_size=20)
dropout_handler = DropoutHandler(
heartbeat_timeout=15.0,
max_consecutive_dropouts=2
)
update_validator = UpdateValidator(
max_norm_threshold=5.0,
consistency_window=3
)
aggregator = RobustAggregator(method='trimmed_mean', trim_ratio=0.1)
# Create control tower
tower = FederatedLearningControlTower(
initial_model=initial_model,
cohort_selector=cohort_selector,
dropout_handler=dropout_handler,
update_validator=update_validator,
aggregator=aggregator,
round_timeout=60.0,
min_cohort_size=5
)
# Register mock clients
for i in range(100):
tower.register_client(
client_id=f"client_{i:03d}",
hardware_profile={
'cpu_cores': np.random.randint(2, 8),
'memory_gb': np.random.randint(4, 16),
'device_type': np.random.choice(['mobile', 'tablet', 'laptop', 'desktop'])
}
)
# Run multiple rounds
for round_num in range(5):
print(f"\n{'='*50}")
print(f"Starting Round {round_num + 1}")
print(f"{'='*50}")
try:
round_result = await tower.execute_round()
print(f"Round completed: {round_result.valid_updates}/{round_result.expected_updates} valid updates")
print(f"Dropouts: {len(round_result.dropout_clients)}")
print(f"Validation failures: {len(round_result.validation_failures)}")
# Print system status every 3 rounds
if (round_num + 1) % 3 == 0:
status = tower.get_system_status()
print(f"\nSystem Status:")
print(f" Success rate: {status['global_metrics']['aggregation_success_rate']/status['global_metrics']['total_rounds']*100:.1f}%")
print(f" Current dropout rate: {status['dropout_stats']['dropout_rate']*100:.1f}%")
print(f" Avg round time: {status['global_metrics']['avg_round_time']:.1f}s")
except StopIteration:
break
# Save final checkpoint
tower.save_checkpoint('fl_checkpoint.json')
print("\nTraining completed and checkpoint saved!")
if __name__ == "__main__":
asyncio.run(example_usage())