Skip to content

Commit

Permalink
Remove prints, add logs
Browse files Browse the repository at this point in the history
  • Loading branch information
edogab33 committed Dec 21, 2023
1 parent 8ae7ceb commit 552f3e3
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 20 deletions.
4 changes: 1 addition & 3 deletions baselines/flanders/flanders/attacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,7 @@ def lie_attack(
s = math.floor((n / 2) + 1) - m # number of supporters

z_max = norm.cdf((n - m - s) / (n - m))
print(f"z_max: {z_max}")
print(f"n: {n}, m: {m}, s: {s}")


for proxy, fitres in ordered_results:
if states[fitres.metrics["cid"]]:
mul_std = [layer * z_max for layer in grads_stdev]
Expand Down
23 changes: 12 additions & 11 deletions baselines/flanders/flanders/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
Scalar,
parameters_to_ndarrays,
)

from flwr.common.logger import log
from flwr.server.client_proxy import ClientProxy

Expand Down Expand Up @@ -183,7 +184,7 @@ def fit_round(
size = self.num_malicious
if self.warmup_rounds > server_round:
size = 0
print(f"fit_round - Selecting {size} malicious clients")
log(INFO, f"Selecting {size} malicious clients")
self.malicious_lst = np.random.choice(
[proxy.cid for proxy, _ in client_instructions], size=size, replace=False
)
Expand All @@ -201,7 +202,7 @@ def fit_round(
ins.config["malicious"] = False

for proxy, ins in client_instructions:
print(f"fit_round - Client {proxy.cid} malicious: {ins.config['malicious']}")
log(INFO, f"Client {proxy.cid} malicious: {ins.config['malicious']}")
# Collect `fit` results from all clients participating in this round
results, failures = fit_clients(
client_instructions=client_instructions,
Expand Down Expand Up @@ -232,11 +233,11 @@ def fit_round(

params = params[self.params_indexes]

print(f"fit_round 1 - Saving parameters of client {fitres.metrics['cid']} with shape {params.shape}")
log(INFO, f"Saving parameters of client {fitres.metrics['cid']} with shape {params.shape}")
save_params(params, fitres.metrics['cid'], dir=self.history_dir)

# Re-arrange results in the same order as clients' cids impose
print("fit_round - Re-arranging results in the same order as clients' cids impose")
log(INFO, "Re-arranging results in the same order as clients' cids impose")
ordered_results[int(fitres.metrics['cid'])] = (proxy, fitres)

# Initialize aggregated_parameters if it is the first round
Expand All @@ -249,7 +250,7 @@ def fit_round(
# Apply attack function
# the server simulates an attacker that controls a fraction of the clients
if self.attack_fn is not None and server_round > self.warmup_rounds:
print("fit_round - Applying attack function")
log(INFO, "Applying attack function")
results, others = self.attack_fn(
ordered_results, clients_state, omniscent=self.omniscent, magnitude=self.magnitude,
w_re=self.aggregated_parameters, malicious_selected=self.malicious_selected,
Expand All @@ -266,24 +267,24 @@ def fit_round(
params = flatten_params(parameters_to_ndarrays(fitres.parameters))[self.params_indexes]
else:
params = flatten_params(parameters_to_ndarrays(fitres.parameters))
print(f"fit_round 2 - Saving parameters of client {fitres.metrics['cid']} with shape {params.shape}")
log(INFO, f"Saving parameters of client {fitres.metrics['cid']} with shape {params.shape}")
save_params(params, fitres.metrics['cid'], dir=self.history_dir, remove_last=True)
else:
results = ordered_results
others = {}

# Sort clients states
clients_state = {k: clients_state[k] for k in sorted(clients_state)}
print(f"fit_round - Clients state: {clients_state}")
log(INFO, f"Clients state: {clients_state}")

# Aggregate training results
print("fit_round - Aggregating training results")
log(INFO, "fit_round - Aggregating training results")
aggregated_result = self.strategy.aggregate_fit(server_round, results, failures, clients_state)

parameters_aggregated, metrics_aggregated, good_clients_idx, malicious_clients_idx = aggregated_result
print(f"fit_round - Malicious clients: {malicious_clients_idx}")
log(INFO, f"Malicious clients: {malicious_clients_idx}")

print(f"aggregate_fit - clients_state: {clients_state}")
log(INFO, f"clients_state: {clients_state}")
for idx in good_clients_idx:
if clients_state[str(idx)]:
self.malicious_selected = True
Expand All @@ -294,7 +295,7 @@ def fit_round(
# For clients detected as malicious, set their parameters to be the averaged ones in their files
# otherwise the forecasting in next round won't be reliable
if self.warmup_rounds > server_round:
print(f"fit_round - Saving parameters of clients")
log(INFO, f"Saving parameters of clients")
for idx in malicious_clients_idx:
if self.sampling > 0:
new_params = flatten_params(parameters_to_ndarrays(parameters_aggregated))[self.params_indexes]
Expand Down
14 changes: 8 additions & 6 deletions baselines/flanders/flanders/strategy.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import numpy as np
from logging import INFO
from flwr.common.logger import log

from typing import Callable, Dict, List, Optional, Tuple, Union
from flwr.server.strategy.fedavg import FedAvg
Expand Down Expand Up @@ -152,21 +154,21 @@ def aggregate_fit(

M_hat = M[:,:,-1].copy()
pred_step = 1
print(f"aggregate_fit - Computing MAR on M {M.shape}")
log(INFO, f"Computing MAR on M {M.shape}")
Mr = mar(M[:,:,:-1], pred_step, maxiter=self.maxiter, alpha=self.alpha, beta=self.beta)

print("aggregate_fit - Computing anomaly scores")
log(INFO, "Computing anomaly scores")
anomaly_scores = self.distance_function(M_hat, Mr[:,:,0])
print(f"aggregate_fit - Anomaly scores: {anomaly_scores}")
log(INFO, f"Anomaly scores: {anomaly_scores}")

print("aggregate_fit - Selecting good clients")
log(INFO, "Selecting good clients")
good_clients_idx = sorted(np.argsort(anomaly_scores)[:self.to_keep])
malicious_clients_idx = sorted(np.argsort(anomaly_scores)[self.to_keep:])
results = np.array(results)[good_clients_idx].tolist()
print(f"aggregate_fit - Good clients: {good_clients_idx}")
log(INFO, f"Good clients: {good_clients_idx}")

# Apply FedAvg for the remaining clients
print("aggregate_fit - Applying FedAvg for the remaining clients")
log(INFO, "Applying FedAvg for the remaining clients")
parameters_aggregated, metrics_aggregated = super().aggregate_fit(server_round, results, failures)
else:
# Apply FedAvg on every clients' params during the first round
Expand Down

0 comments on commit 552f3e3

Please sign in to comment.