federated_main.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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. if __name__ == '__main__':
  17. start_time = time.time()
  18. # define paths
  19. path_project = os.path.abspath('..')
  20. logger = SummaryWriter('../logs')
  21. args = args_parser()
  22. exp_details(args)
  23. if args.gpu:
  24. torch.cuda.set_device(args.gpu)
  25. device = 'cuda' if args.gpu else 'cpu'
  26. # load dataset and user groups
  27. train_dataset, test_dataset, user_groups = get_dataset(args)
  28. # BUILD MODEL
  29. if args.model == 'cnn':
  30. # Convolutional neural netork
  31. if args.dataset == 'mnist':
  32. global_model = CNNMnist(args=args)
  33. elif args.dataset == 'fmnist':
  34. global_model = CNNFashion_Mnist(args=args)
  35. elif args.dataset == 'cifar':
  36. global_model = CNNCifar(args=args)
  37. elif args.model == 'mlp':
  38. # Multi-layer preceptron
  39. img_size = train_dataset[0][0].shape
  40. len_in = 1
  41. for x in img_size:
  42. len_in *= x
  43. global_model = MLP(dim_in=len_in, dim_hidden=64,
  44. dim_out=args.num_classes)
  45. else:
  46. exit('Error: unrecognized model')
  47. # Set the model to train and send it to device.
  48. global_model.to(device)
  49. global_model.train()
  50. print(global_model)
  51. # copy weights
  52. global_weights = global_model.state_dict()
  53. # Training
  54. train_loss, train_accuracy = [], []
  55. val_acc_list, net_list = [], []
  56. cv_loss, cv_acc = [], []
  57. print_every = 2
  58. val_loss_pre, counter = 0, 0
  59. for epoch in tqdm(range(args.epochs)): # global training epochs
  60. local_weights, local_losses = [], [] # init empty local weights and local losses
  61. print(f'\n | Global Training Round : {epoch+1} |\n') # starting with | Global Training Round : 1 |
  62. """
  63. 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.
  64. 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.
  65. """
  66. # ============== TRAIN ==============
  67. global_model.train()
  68. m = max(int(args.frac * args.num_users), 1) # C = args.frac. Setting number of clients m for training
  69. 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.
  70. for idx in idxs_users: # For each client in the subset.
  71. local_model = LocalUpdate(args=args, dataset=train_dataset,
  72. idxs=user_groups[idx], logger=logger)
  73. w, loss = local_model.update_weights( # update_weights() contain multiple prints
  74. model=copy.deepcopy(global_model), global_round=epoch) # w = local model weights
  75. local_weights.append(copy.deepcopy(w))
  76. local_losses.append(copy.deepcopy(loss))
  77. # Averaging m local client weights
  78. global_weights = average_weights(local_weights)
  79. # update global weights
  80. global_model.load_state_dict(global_weights)
  81. loss_avg = sum(local_losses) / len(local_losses)
  82. train_loss.append(loss_avg) # Performance measure
  83. # ============== EVAL ==============
  84. # Calculate avg training accuracy over all users at every epoch
  85. list_acc, list_loss = [], []
  86. global_model.eval() # must set your model into evaluation mode when computing model output values if dropout or bach norm used for training.
  87. for c in range(args.num_users): # 0 to 99
  88. local_model = LocalUpdate(args=args, dataset=train_dataset,
  89. # idxs=user_groups[idx], logger=logger)
  90. # Fix error idxs=user_groups[idx] to idxs=user_groups[c]
  91. local_model = LocalUpdate(args=args, dataset=train_dataset,
  92. idxs=user_groups[idx], logger=logger)
  93. acc, loss = local_model.inference(model=global_model)
  94. list_acc.append(acc)
  95. list_loss.append(loss)
  96. train_accuracy.append(sum(list_acc)/len(list_acc)) # Performance measure
  97. # print global training loss after every 'i' rounds
  98. if (epoch+1) % print_every == 0: # If print_every=2, => print every 2 rounds
  99. print(f' \nAvg Training Stats after {epoch+1} global rounds:')
  100. print(f'Training Loss : {np.mean(np.array(train_loss))}')
  101. print('Train Accuracy: {:.2f}% \n'.format(100*train_accuracy[-1]))
  102. # Test inference after completion of training
  103. test_acc, test_loss = test_inference(args, global_model, test_dataset)
  104. print(f' \n Results after {args.epochs} global rounds of training:')
  105. print("|---- Avg Train Accuracy: {:.2f}%".format(100*train_accuracy[-1]))
  106. print("|---- Test Accuracy: {:.2f}%".format(100*test_acc))
  107. # Saving the objects train_loss and train_accuracy:
  108. file_name = '../save/objects/{}_{}_{}_C[{}]_iid[{}]_E[{}]_B[{}].pkl'.\
  109. format(args.dataset, args.model, args.epochs, args.frac, args.iid,
  110. args.local_ep, args.local_bs)
  111. with open(file_name, 'wb') as f:
  112. pickle.dump([train_loss, train_accuracy], f)
  113. print('\n Total Run Time: {0:0.4f}'.format(time.time()-start_time))
  114. # PLOTTING (optional)
  115. # import matplotlib
  116. # import matplotlib.pyplot as plt
  117. # matplotlib.use('Agg')
  118. # Plot Loss curve
  119. # plt.figure()
  120. # plt.title('Training Loss vs Communication rounds')
  121. # plt.plot(range(len(train_loss)), train_loss, color='r')
  122. # plt.ylabel('Training loss')
  123. # plt.xlabel('Communication Rounds')
  124. # plt.savefig('../save/fed_{}_{}_{}_C[{}]_iid[{}]_E[{}]_B[{}]_loss.png'.
  125. # format(args.dataset, args.model, args.epochs, args.frac,
  126. # args.iid, args.local_ep, args.local_bs))
  127. #
  128. # # Plot Average Accuracy vs Communication rounds
  129. # plt.figure()
  130. # plt.title('Average Accuracy vs Communication rounds')
  131. # plt.plot(range(len(train_accuracy)), train_accuracy, color='k')
  132. # plt.ylabel('Average Accuracy')
  133. # plt.xlabel('Communication Rounds')
  134. # plt.savefig('../save/fed_{}_{}_{}_C[{}]_iid[{}]_E[{}]_B[{}]_acc.png'.
  135. # format(args.dataset, args.model, args.epochs, args.frac,
  136. # args.iid, args.local_ep, args.local_bs))