federated_main_fp16.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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 torch.utils.tensorboard import SummaryWriter
  13. from options import args_parser
  14. from update import LocalUpdate, test_inference
  15. from models import MLP, CNNMnist, CNNFashion_Mnist, CNNCifar
  16. from utils import get_dataset, average_weights, exp_details, set_device, build_model
  17. # os.environ['CUDA_VISIBLE_DEVICES'] ='0'
  18. from sys import exit
  19. #from torchsummary import summary
  20. if __name__ == '__main__':
  21. start_time = time.time()
  22. # define paths
  23. path_project = os.path.abspath('..')
  24. logger = SummaryWriter('../logs')
  25. args = args_parser()
  26. exp_details(args)
  27. # Select CPU or GPU
  28. device = set_device(args)
  29. # load dataset and user groups
  30. train_dataset, test_dataset, user_groups = get_dataset(args)
  31. # BUILD MODEL
  32. global_model = build_model(args, train_dataset)
  33. # Set the model to train and send it to device.
  34. global_model.to(device)
  35. # Set model to use Floating Point 16
  36. global_model.to(dtype=torch.float16) ##########
  37. global_model.train()
  38. print(global_model)
  39. # MODEL PARAM SUMMARY
  40. pytorch_total_params = sum(p.numel() for p in global_model.parameters())
  41. print("Model total number of parameters: ", pytorch_total_params)
  42. # print(global_model.parameters())
  43. # copy weights
  44. global_weights = global_model.state_dict()
  45. # Training
  46. train_loss, train_accuracy = [], []
  47. val_acc_list, net_list = [], []
  48. cv_loss, cv_acc = [], []
  49. print_every = 1
  50. val_loss_pre, counter = 0, 0
  51. testacc_check, epoch = 0, 0
  52. # for epoch in tqdm(range(args.epochs)): # global training epochs
  53. for epoch in range(args.epochs):
  54. # while testacc_check < args.test_acc or epoch < args.epochs:
  55. # while testacc_check < args.test_acc:
  56. local_weights, local_losses = [], [] # init empty local weights and local losses
  57. print(f'\n | Global Training Round : {epoch+1} |\n') # starting with | Global Training Round : 1 |
  58. """
  59. 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.
  60. 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.
  61. """
  62. # ============== TRAIN ==============
  63. global_model.train()
  64. m = max(int(args.frac * args.num_users), 1) # C = args.frac. Setting number of clients m for training
  65. 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.
  66. for idx in idxs_users: # For each client in the subset.
  67. local_model = LocalUpdate(args=args, dataset=train_dataset,
  68. idxs=user_groups[idx], logger=logger)
  69. w, loss = local_model.update_weights( # update_weights() contain multiple prints
  70. model=copy.deepcopy(global_model), global_round=epoch,dtype=torch.float16)
  71. # w = local model weights
  72. local_weights.append(copy.deepcopy(w))
  73. local_losses.append(copy.deepcopy(loss))
  74. # Averaging m local client weights
  75. global_weights = average_weights(local_weights)
  76. # update global weights
  77. global_model.load_state_dict(global_weights)
  78. loss_avg = sum(local_losses) / len(local_losses)
  79. train_loss.append(loss_avg) # Performance measure
  80. # ============== EVAL ==============
  81. # Calculate avg training accuracy over all users at every epoch
  82. list_acc, list_loss = [], []
  83. global_model.eval() # must set your model into evaluation mode when computing model output values if dropout or bach norm used for training.
  84. for c in range(args.num_users): # 0 to 99
  85. # local_model = LocalUpdate(args=args, dataset=train_dataset,
  86. # idxs=user_groups[idx], logger=logger)
  87. # Fix error idxs=user_groups[idx] to idxs=user_groups[c]
  88. local_model = LocalUpdate(args=args, dataset=train_dataset,
  89. idxs=user_groups[c], logger=logger)
  90. acc, loss = local_model.inference(model=global_model, dtype=torch.float16)
  91. list_acc.append(acc)
  92. list_loss.append(loss)
  93. train_accuracy.append(sum(list_acc)/len(list_acc)) # Performance measure
  94. # Add
  95. testacc_check = 100*train_accuracy[-1]
  96. epoch = epoch + 1
  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, dtype=torch.float16)
  104. print(f' \n Results after {epoch} 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_fp16/FL_{}_{}_{}_lr[{}]_C[{}]_iid[{}]_E[{}]_B[{}]_FP16.pkl'.\
  109. format(args.dataset, args.model, epoch, args.lr, 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))