You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

eval.py 9.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """
  16. ##############test densenet example#################
  17. python eval.py --data_dir /PATH/TO/DATASET --pretrained /PATH/TO/CHECKPOINT
  18. """
  19. import os
  20. import argparse
  21. import datetime
  22. import glob
  23. import numpy as np
  24. from mindspore import context
  25. import mindspore.nn as nn
  26. from mindspore import Tensor
  27. from mindspore.communication.management import init, get_rank, get_group_size, release
  28. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  29. from mindspore.ops import operations as P
  30. from mindspore.ops import functional as F
  31. from mindspore.common import dtype as mstype
  32. from src.utils.logging import get_logger
  33. from src.datasets import classification_dataset
  34. from src.network import DenseNet121
  35. from src.config import config
  36. devid = int(os.getenv('DEVICE_ID'))
  37. context.set_context(mode=context.GRAPH_MODE, device_target="Davinci",
  38. save_graphs=True, device_id=devid)
  39. class ParameterReduce(nn.Cell):
  40. """
  41. reduce parameter
  42. """
  43. def __init__(self):
  44. super(ParameterReduce, self).__init__()
  45. self.cast = P.Cast()
  46. self.reduce = P.AllReduce()
  47. def construct(self, x):
  48. one = self.cast(F.scalar_to_array(1.0), mstype.float32)
  49. out = x * one
  50. ret = self.reduce(out)
  51. return ret
  52. def parse_args(cloud_args=None):
  53. """
  54. parse args
  55. """
  56. parser = argparse.ArgumentParser('mindspore classification test')
  57. # dataset related
  58. parser.add_argument('--data_dir', type=str, default='', help='eval data dir')
  59. parser.add_argument('--num_classes', type=int, default=1000, help='num of classes in dataset')
  60. parser.add_argument('--image_size', type=str, default='224,224', help='image size of the dataset')
  61. # network related
  62. parser.add_argument('--backbone', default='resnet50', help='backbone')
  63. parser.add_argument('--pretrained', default='', type=str, help='fully path of pretrained model to load.'
  64. 'If it is a direction, it will test all ckpt')
  65. # logging related
  66. parser.add_argument('--log_path', type=str, default='outputs/', help='path to save log')
  67. parser.add_argument('--is_distributed', type=int, default=1, help='if multi device')
  68. parser.add_argument('--rank', type=int, default=0, help='local rank of distributed')
  69. parser.add_argument('--group_size', type=int, default=1, help='world size of distributed')
  70. # roma obs
  71. parser.add_argument('--train_url', type=str, default="", help='train url')
  72. args, _ = parser.parse_known_args()
  73. args = merge_args(args, cloud_args)
  74. args.per_batch_size = config.per_batch_size
  75. args.image_size = list(map(int, args.image_size.split(',')))
  76. return args
  77. def get_top5_acc(top5_arg, gt_class):
  78. sub_count = 0
  79. for top5, gt in zip(top5_arg, gt_class):
  80. if gt in top5:
  81. sub_count += 1
  82. return sub_count
  83. def merge_args(args, cloud_args):
  84. """
  85. merge args and cloud_args
  86. """
  87. args_dict = vars(args)
  88. if isinstance(cloud_args, dict):
  89. for key in cloud_args.keys():
  90. val = cloud_args[key]
  91. if key in args_dict and val:
  92. arg_type = type(args_dict[key])
  93. if arg_type is not type(None):
  94. val = arg_type(val)
  95. args_dict[key] = val
  96. return args
  97. def test(cloud_args=None):
  98. """
  99. network eval function. Get top1 and top5 ACC from classification.
  100. The result will be save at [./outputs] by default.
  101. """
  102. args = parse_args(cloud_args)
  103. # init distributed
  104. if args.is_distributed:
  105. init()
  106. args.rank = get_rank()
  107. args.group_size = get_group_size()
  108. args.outputs_dir = os.path.join(args.log_path,
  109. datetime.datetime.now().strftime('%Y-%m-%d_time_%H_%M_%S'))
  110. args.logger = get_logger(args.outputs_dir, args.rank)
  111. args.logger.save_args(args)
  112. # network
  113. args.logger.important_info('start create network')
  114. if os.path.isdir(args.pretrained):
  115. models = list(glob.glob(os.path.join(args.pretrained, '*.ckpt')))
  116. f = lambda x: -1 * int(os.path.splitext(os.path.split(x)[-1])[0].split('-')[-1].split('_')[0])
  117. args.models = sorted(models, key=f)
  118. else:
  119. args.models = [args.pretrained,]
  120. for model in args.models:
  121. de_dataset = classification_dataset(args.data_dir, image_size=args.image_size,
  122. per_batch_size=args.per_batch_size,
  123. max_epoch=1, rank=args.rank, group_size=args.group_size,
  124. mode='eval')
  125. eval_dataloader = de_dataset.create_tuple_iterator()
  126. network = DenseNet121(args.num_classes)
  127. param_dict = load_checkpoint(model)
  128. param_dict_new = {}
  129. for key, values in param_dict.items():
  130. if key.startswith('moments.'):
  131. continue
  132. elif key.startswith('network.'):
  133. param_dict_new[key[8:]] = values
  134. else:
  135. param_dict_new[key] = values
  136. load_param_into_net(network, param_dict_new)
  137. args.logger.info('load model {} success'.format(model))
  138. network.add_flags_recursive(fp16=True)
  139. img_tot = 0
  140. top1_correct = 0
  141. top5_correct = 0
  142. network.set_train(False)
  143. for data, gt_classes in eval_dataloader:
  144. output = network(Tensor(data, mstype.float32))
  145. output = output.asnumpy()
  146. gt_classes = gt_classes.asnumpy()
  147. top1_output = np.argmax(output, (-1))
  148. top5_output = np.argsort(output)[:, -5:]
  149. t1_correct = np.equal(top1_output, gt_classes).sum()
  150. top1_correct += t1_correct
  151. top5_correct += get_top5_acc(top5_output, gt_classes)
  152. img_tot += args.per_batch_size
  153. results = [[top1_correct], [top5_correct], [img_tot]]
  154. args.logger.info('before results={}'.format(results))
  155. if args.is_distributed:
  156. model_md5 = model.replace('/', '')
  157. tmp_dir = '../cache'
  158. if not os.path.exists(tmp_dir):
  159. os.mkdir(tmp_dir)
  160. top1_correct_npy = '{}/top1_rank_{}_{}.npy'.format(tmp_dir, args.rank, model_md5)
  161. top5_correct_npy = '{}/top5_rank_{}_{}.npy'.format(tmp_dir, args.rank, model_md5)
  162. img_tot_npy = '{}/img_tot_rank_{}_{}.npy'.format(tmp_dir, args.rank, model_md5)
  163. np.save(top1_correct_npy, top1_correct)
  164. np.save(top5_correct_npy, top5_correct)
  165. np.save(img_tot_npy, img_tot)
  166. while True:
  167. rank_ok = True
  168. for other_rank in range(args.group_size):
  169. top1_correct_npy = '{}/top1_rank_{}_{}.npy'.format(tmp_dir, other_rank, model_md5)
  170. top5_correct_npy = '{}/top5_rank_{}_{}.npy'.format(tmp_dir, other_rank, model_md5)
  171. img_tot_npy = '{}/img_tot_rank_{}_{}.npy'.format(tmp_dir, other_rank, model_md5)
  172. if not os.path.exists(top1_correct_npy) or not os.path.exists(top5_correct_npy) \
  173. or not os.path.exists(img_tot_npy):
  174. rank_ok = False
  175. if rank_ok:
  176. break
  177. top1_correct_all = 0
  178. top5_correct_all = 0
  179. img_tot_all = 0
  180. for other_rank in range(args.group_size):
  181. top1_correct_npy = '{}/top1_rank_{}_{}.npy'.format(tmp_dir, other_rank, model_md5)
  182. top5_correct_npy = '{}/top5_rank_{}_{}.npy'.format(tmp_dir, other_rank, model_md5)
  183. img_tot_npy = '{}/img_tot_rank_{}_{}.npy'.format(tmp_dir, other_rank, model_md5)
  184. top1_correct_all += np.load(top1_correct_npy)
  185. top5_correct_all += np.load(top5_correct_npy)
  186. img_tot_all += np.load(img_tot_npy)
  187. results = [[top1_correct_all], [top5_correct_all], [img_tot_all]]
  188. results = np.array(results)
  189. else:
  190. results = np.array(results)
  191. args.logger.info('after results={}'.format(results))
  192. top1_correct = results[0, 0]
  193. top5_correct = results[1, 0]
  194. img_tot = results[2, 0]
  195. acc1 = 100.0 * top1_correct / img_tot
  196. acc5 = 100.0 * top5_correct / img_tot
  197. args.logger.info('after allreduce eval: top1_correct={}, tot={}, acc={:.2f}%'.format(top1_correct,
  198. img_tot,
  199. acc1))
  200. args.logger.info('after allreduce eval: top5_correct={}, tot={}, acc={:.2f}%'.format(top5_correct,
  201. img_tot,
  202. acc5))
  203. if args.is_distributed:
  204. release()
  205. if __name__ == "__main__":
  206. test()