serverrep.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. from flcore.clients.clientrep import clientRep
  2. from flcore.servers.serverbase import Server
  3. import os
  4. import logging
  5. import copy
  6. class FedRep(Server):
  7. def __init__(self, args, times):
  8. super().__init__(args, times)
  9. self.message_hp = f"{args.algorithm}, lr:{args.local_learning_rate:.5f}"
  10. clientObj = clientRep
  11. self.message_hp_dash = self.message_hp.replace(", ", "-")
  12. self.hist_result_fn = os.path.join(args.hist_dir, f"{self.actual_dataset}-{self.message_hp_dash}-{args.goal}-{self.times}.h5")
  13. self.set_clients(args, clientObj)
  14. print(f"\nJoin ratio / total clients: {self.join_ratio} / {self.num_clients}")
  15. print("Finished creating server and clients.")
  16. self.Budget = []
  17. def train(self):
  18. for i in range(self.global_rounds):
  19. self.selected_clients = self.select_clients()
  20. self.send_models()
  21. print(f"\n------------- Round number: [{i+1:3d}/{self.global_rounds}]-------------")
  22. print(f"==> Training for {len(self.selected_clients)} clients...", flush=True)
  23. for client in self.selected_clients:
  24. client.train()
  25. self.receive_models()
  26. self.aggregate_parameters()
  27. if i%self.eval_gap == 0:
  28. print("==> Evaluating personalized models...", flush=True)
  29. self.send_models(mode="all")
  30. self.evaluate(self.global_model)
  31. if i == 80:
  32. self.check_early_stopping()
  33. print(f"==> Best mean personalized accuracy: {self.best_mean_test_acc*100:.2f}%", flush=True)
  34. self.save_results(fn=self.hist_result_fn)
  35. message_res = f"\ttest_acc:{self.best_mean_test_acc:.6f}"
  36. logging.info(self.message_hp + message_res)
  37. # self.save_global_model()
  38. def receive_models(self):
  39. assert (len(self.selected_clients) > 0)
  40. active_train_samples = 0
  41. for client in self.selected_clients:
  42. active_train_samples += client.train_samples
  43. self.uploaded_weights = []
  44. self.uploaded_ids = []
  45. self.uploaded_models = []
  46. for client in self.selected_clients:
  47. self.uploaded_weights.append(client.train_samples / active_train_samples)
  48. self.uploaded_ids.append(client.id)
  49. self.uploaded_models.append(copy.deepcopy(client.model.base))
  50. def prepare_global_model(self):
  51. temp_model = copy.deepcopy(self.global_model) # base
  52. self.global_model = copy.deepcopy(self.clients[0].model)
  53. for p_t, p_g in zip(temp_model.parameters(), self.global_model.base.parameters()):
  54. p_g.data = p_t.data.clone()
  55. for p in self.global_model.predictor.parameters():
  56. p.data.zero_()
  57. for c in self.clients:
  58. for p_g, p_c in zip(self.global_model.predictor.parameters(), c.model.predictor.parameters()):
  59. p_g.data += p_c.data * c.train_samples
  60. return
  61. def train_new_clients(self, epochs=20):
  62. self.global_model = self.global_model.to(self.device)
  63. self.clients = self.new_clients
  64. self.send_models(mode="all")
  65. self.reset_records()
  66. for c in self.clients:
  67. c.model = copy.deepcopy(self.global_model)
  68. for epoch_idx in range(epochs):
  69. for c in self.clients:
  70. c.standard_train()
  71. print(f"==> New clients epoch: [{epoch_idx+1:2d}/{epochs}] | Evaluating local models...", flush=True)
  72. self.evaluate()
  73. print(f"==> Best mean global accuracy: {self.best_mean_test_acc*100:.2f}%", flush=True)
  74. self.save_results(fn=self.hist_result_fn)
  75. message_res = f"\tnew_clients_test_acc:{self.best_mean_test_acc:.6f}"
  76. logging.info(self.message_hp + message_res)