serverapfl.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. from flcore.clients.clientapfl import clientAPFL
  2. from flcore.servers.serverbase import Server
  3. import logging
  4. import os
  5. class APFL(Server):
  6. def __init__(self, args, times):
  7. super().__init__(args, times)
  8. self.message_hp = f"{args.algorithm}, lr:{args.local_learning_rate:.5f}, alpha:{args.alpha:.2f}"
  9. clientObj = clientAPFL
  10. self.message_hp_dash = self.message_hp.replace(", ", "-")
  11. self.hist_result_fn = os.path.join(args.hist_dir, f"{self.actual_dataset}-{self.message_hp_dash}-{args.goal}-{self.times}.h5")
  12. self.set_clients(args, clientObj)
  13. print(f"\nJoin ratio / total clients: {self.join_ratio} / {self.num_clients}")
  14. print("Finished creating server and clients.")
  15. def train(self):
  16. for i in range(self.global_rounds):
  17. self.selected_clients = self.select_clients()
  18. self.send_models()
  19. print(f"\n------------- Round number: [{i+1:3d}/{self.global_rounds}]-------------")
  20. print(f"==> Training for {len(self.selected_clients)} clients...", flush=True)
  21. for client in self.selected_clients:
  22. client.train()
  23. self.receive_models()
  24. self.aggregate_parameters()
  25. if i % self.eval_gap == 0:
  26. print("==> Evaluating personalized models...", flush=True)
  27. self.send_models(mode="all")
  28. self.evaluate()
  29. if i == 80:
  30. self.check_early_stopping()
  31. print(f"\n==> Best mean personalized accuracy: {self.best_mean_test_acc*100:.2f}%", flush=True)
  32. self.save_results(fn=self.hist_result_fn)
  33. message_res = f"\ttest_acc:{self.best_mean_test_acc:.6f}"
  34. logging.info(self.message_hp + message_res)