federated_main.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Python version: 3.6
  4. import os
  5. import copy
  6. import time
  7. import pickle
  8. import numpy as np
  9. from tqdm import tqdm
  10. import torch
  11. from tensorboardX import SummaryWriter
  12. from options import args_parser
  13. from update import LocalUpdate, test_inference
  14. from models import MLP, CNNMnist, CNNFashion_Mnist, CNNCifar
  15. from utils import get_dataset, average_weights, exp_details
  16. # os.environ['CUDA_VISIBLE_DEVICES'] ='0'
  17. if __name__ == '__main__':
  18. start_time = time.time()
  19. # define paths
  20. path_project = os.path.abspath('..')
  21. logger = SummaryWriter('../logs')
  22. args = args_parser()
  23. exp_details(args)
  24. if args.gpu:
  25. torch.cuda.set_device(args.gpu)
  26. # torch.cuda.set_device(0)
  27. device = 'cuda' if args.gpu else 'cpu'
  28. # load dataset and user groups
  29. train_dataset, test_dataset, user_groups = get_dataset(args)
  30. # BUILD MODEL
  31. if args.model == 'cnn':
  32. # Convolutional neural netork
  33. if args.dataset == 'mnist':
  34. global_model = CNNMnist(args=args)
  35. elif args.dataset == 'fmnist':
  36. global_model = CNNFashion_Mnist(args=args)
  37. elif args.dataset == 'cifar':
  38. global_model = CNNCifar(args=args)
  39. elif args.model == 'mlp':
  40. # Multi-layer preceptron
  41. img_size = train_dataset[0][0].shape
  42. len_in = 1
  43. for x in img_size:
  44. len_in *= x
  45. global_model = MLP(dim_in=len_in, dim_hidden=args.mlpdim,
  46. dim_out=args.num_classes)
  47. else:
  48. exit('Error: unrecognized model')
  49. # Set the model to train and send it to device.
  50. global_model.to(device)
  51. global_model.train()
  52. print(global_model)
  53. # MODEL PARAM SUMMARY
  54. pytorch_total_params = sum(p.numel() for p in global_model.parameters())
  55. print("Model total number of parameters: ", pytorch_total_params)
  56. # print(global_model.parameters())
  57. # copy weights
  58. global_weights = global_model.state_dict()
  59. # Training
  60. train_loss, train_accuracy = [], []
  61. val_acc_list, net_list = [], []
  62. cv_loss, cv_acc = [], []
  63. print_every = 1
  64. val_loss_pre, counter = 0, 0
  65. testacc_check, epoch = 0, 0
  66. # for epoch in tqdm(range(args.epochs)): # global training epochs
  67. for epoch in range(args.epochs):
  68. # while testacc_check < args.test_acc or epoch < args.epochs:
  69. # while testacc_check < args.test_acc:
  70. local_weights, local_losses = [], [] # init empty local weights and local losses
  71. print(f'\n | Global Training Round : {epoch+1} |\n') # starting with | Global Training Round : 1 |
  72. """
  73. model.train() tells your model that you are training the model. So effectively layers like dropout, batchnorm etc. which behave different on the train and test procedures know what is going on and hence can behave accordingly.
  74. More details: It sets the mode to train (see source code). You can call either model.eval() or model.train(mode=False) to tell that you are testing. It is somewhat intuitive to expect train function to train model but it does not do that. It just sets the mode.
  75. """
  76. # ============== TRAIN ==============
  77. global_model.train()
  78. m = max(int(args.frac * args.num_users), 1) # C = args.frac. Setting number of clients m for training
  79. idxs_users = np.random.choice(range(args.num_users), m, replace=False) # args.num_users=100 total clients. Choosing a random array of indices. Subset of clients.
  80. for idx in idxs_users: # For each client in the subset.
  81. local_model = LocalUpdate(args=args, dataset=train_dataset,
  82. idxs=user_groups[idx], logger=logger)
  83. w, loss = local_model.update_weights( # update_weights() contain multiple prints
  84. model=copy.deepcopy(global_model), global_round=epoch) # w = local model weights
  85. local_weights.append(copy.deepcopy(w))
  86. local_losses.append(copy.deepcopy(loss))
  87. # Averaging m local client weights
  88. global_weights = average_weights(local_weights)
  89. # update global weights
  90. global_model.load_state_dict(global_weights)
  91. loss_avg = sum(local_losses) / len(local_losses)
  92. train_loss.append(loss_avg) # Performance measure
  93. # ============== EVAL ==============
  94. # Calculate avg training accuracy over all users at every epoch
  95. list_acc, list_loss = [], []
  96. global_model.eval() # must set your model into evaluation mode when computing model output values if dropout or bach norm used for training.
  97. for c in range(args.num_users): # 0 to 99
  98. # local_model = LocalUpdate(args=args, dataset=train_dataset,
  99. # idxs=user_groups[idx], logger=logger)
  100. # Fix error idxs=user_groups[idx] to idxs=user_groups[c]
  101. local_model = LocalUpdate(args=args, dataset=train_dataset,
  102. idxs=user_groups[c], logger=logger)
  103. acc, loss = local_model.inference(model=global_model)
  104. list_acc.append(acc)
  105. list_loss.append(loss)
  106. train_accuracy.append(sum(list_acc)/len(list_acc)) # Performance measure
  107. # Add
  108. testacc_check = 100*train_accuracy[-1]
  109. epoch = epoch + 1
  110. # print global training loss after every 'i' rounds
  111. if (epoch+1) % print_every == 0: # If print_every=2, => print every 2 rounds
  112. print(f' \nAvg Training Stats after {epoch+1} global rounds:')
  113. print(f'Training Loss : {np.mean(np.array(train_loss))}')
  114. print('Train Accuracy: {:.2f}% \n'.format(100*train_accuracy[-1]))
  115. # Test inference after completion of training
  116. test_acc, test_loss = test_inference(args, global_model, test_dataset)
  117. print(f' \n Results after {epoch} global rounds of training:')
  118. print("|---- Avg Train Accuracy: {:.2f}%".format(100*train_accuracy[-1]))
  119. print("|---- Test Accuracy: {:.2f}%".format(100*test_acc))
  120. # Saving the objects train_loss and train_accuracy:
  121. file_name = '../save/objects/FL_{}_{}_{}_lr[{}]_C[{}]_iid[{}]_E[{}]_B[{}].pkl'.\
  122. format(args.dataset, args.model, epoch, args.lr, args.frac, args.iid,
  123. args.local_ep, args.local_bs)
  124. with open(file_name, 'wb') as f:
  125. pickle.dump([train_loss, train_accuracy], f)
  126. print('\n Total Run Time: {0:0.4f}'.format(time.time()-start_time))
  127. # PLOTTING (optional)
  128. # import matplotlib
  129. # import matplotlib.pyplot as plt
  130. # matplotlib.use('Agg')
  131. # Plot Loss curve
  132. # plt.figure()
  133. # plt.title('Training Loss vs Communication rounds')
  134. # plt.plot(range(len(train_loss)), train_loss, color='r')
  135. # plt.ylabel('Training loss')
  136. # plt.xlabel('Communication Rounds')
  137. # plt.savefig('../save/fed_{}_{}_{}_C[{}]_iid[{}]_E[{}]_B[{}]_loss.png'.
  138. # format(args.dataset, args.model, args.epochs, args.frac,
  139. # args.iid, args.local_ep, args.local_bs))
  140. #
  141. # # Plot Average Accuracy vs Communication rounds
  142. # plt.figure()
  143. # plt.title('Average Accuracy vs Communication rounds')
  144. # plt.plot(range(len(train_accuracy)), train_accuracy, color='k')
  145. # plt.ylabel('Average Accuracy')
  146. # plt.xlabel('Communication Rounds')
  147. # plt.savefig('../save/fed_{}_{}_{}_C[{}]_iid[{}]_E[{}]_B[{}]_acc.png'.
  148. # format(args.dataset, args.model, args.epochs, args.frac,
  149. # args.iid, args.local_ep, args.local_bs))