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 10 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. class ParameterReduce(nn.Cell):
  37. """
  38. reduce parameter
  39. """
  40. def __init__(self):
  41. super(ParameterReduce, self).__init__()
  42. self.cast = P.Cast()
  43. self.reduce = P.AllReduce()
  44. def construct(self, x):
  45. one = self.cast(F.scalar_to_array(1.0), mstype.float32)
  46. out = x * one
  47. ret = self.reduce(out)
  48. return ret
  49. def parse_args(cloud_args=None):
  50. """
  51. parse args
  52. """
  53. parser = argparse.ArgumentParser('mindspore classification test')
  54. # dataset related
  55. parser.add_argument('--data_dir', type=str, default='', help='eval data dir')
  56. parser.add_argument('--num_classes', type=int, default=1000, help='num of classes in dataset')
  57. parser.add_argument('--image_size', type=str, default='224,224', help='image size of the dataset')
  58. # network related
  59. parser.add_argument('--backbone', default='resnet50', help='backbone')
  60. parser.add_argument('--pretrained', default='', type=str, help='fully path of pretrained model to load.'
  61. 'If it is a direction, it will test all ckpt')
  62. # logging related
  63. parser.add_argument('--log_path', type=str, default='outputs/', help='path to save log')
  64. parser.add_argument('--is_distributed', type=int, default=1, help='if multi device')
  65. parser.add_argument('--rank', type=int, default=0, help='local rank of distributed')
  66. parser.add_argument('--group_size', type=int, default=1, help='world size of distributed')
  67. # roma obs
  68. parser.add_argument('--train_url', type=str, default="", help='train url')
  69. # platform
  70. parser.add_argument('--device_target', type=str, default='Ascend', choices=('Ascend', 'GPU'), help='device target')
  71. args, _ = parser.parse_known_args()
  72. args = merge_args(args, cloud_args)
  73. args.per_batch_size = config.per_batch_size
  74. args.image_size = list(map(int, args.image_size.split(',')))
  75. return args
  76. def get_top5_acc(top5_arg, gt_class):
  77. sub_count = 0
  78. for top5, gt in zip(top5_arg, gt_class):
  79. if gt in top5:
  80. sub_count += 1
  81. return sub_count
  82. def merge_args(args, cloud_args):
  83. """
  84. merge args and cloud_args
  85. """
  86. args_dict = vars(args)
  87. if isinstance(cloud_args, dict):
  88. for key in cloud_args.keys():
  89. val = cloud_args[key]
  90. if key in args_dict and val:
  91. arg_type = type(args_dict[key])
  92. if arg_type is not type(None):
  93. val = arg_type(val)
  94. args_dict[key] = val
  95. return args
  96. def generate_results(model, rank, group_size, top1_correct, top5_correct, img_tot):
  97. model_md5 = model.replace('/', '')
  98. tmp_dir = '../cache'
  99. if not os.path.exists(tmp_dir):
  100. os.mkdir(tmp_dir)
  101. top1_correct_npy = '{}/top1_rank_{}_{}.npy'.format(tmp_dir, rank, model_md5)
  102. top5_correct_npy = '{}/top5_rank_{}_{}.npy'.format(tmp_dir, rank, model_md5)
  103. img_tot_npy = '{}/img_tot_rank_{}_{}.npy'.format(tmp_dir, rank, model_md5)
  104. np.save(top1_correct_npy, top1_correct)
  105. np.save(top5_correct_npy, top5_correct)
  106. np.save(img_tot_npy, img_tot)
  107. while True:
  108. rank_ok = True
  109. for other_rank in range(group_size):
  110. top1_correct_npy = '{}/top1_rank_{}_{}.npy'.format(tmp_dir, other_rank, model_md5)
  111. top5_correct_npy = '{}/top5_rank_{}_{}.npy'.format(tmp_dir, other_rank, model_md5)
  112. img_tot_npy = '{}/img_tot_rank_{}_{}.npy'.format(tmp_dir, other_rank, model_md5)
  113. if not os.path.exists(top1_correct_npy) or not os.path.exists(top5_correct_npy) \
  114. or not os.path.exists(img_tot_npy):
  115. rank_ok = False
  116. if rank_ok:
  117. break
  118. top1_correct_all = 0
  119. top5_correct_all = 0
  120. img_tot_all = 0
  121. for other_rank in range(group_size):
  122. top1_correct_npy = '{}/top1_rank_{}_{}.npy'.format(tmp_dir, other_rank, model_md5)
  123. top5_correct_npy = '{}/top5_rank_{}_{}.npy'.format(tmp_dir, other_rank, model_md5)
  124. img_tot_npy = '{}/img_tot_rank_{}_{}.npy'.format(tmp_dir, other_rank, model_md5)
  125. top1_correct_all += np.load(top1_correct_npy)
  126. top5_correct_all += np.load(top5_correct_npy)
  127. img_tot_all += np.load(img_tot_npy)
  128. return [[top1_correct_all], [top5_correct_all], [img_tot_all]]
  129. def test(cloud_args=None):
  130. """
  131. network eval function. Get top1 and top5 ACC from classification.
  132. The result will be save at [./outputs] by default.
  133. """
  134. args = parse_args(cloud_args)
  135. context.set_context(mode=context.GRAPH_MODE, device_target=args.device_target,
  136. save_graphs=True)
  137. if args.device_target == 'Ascend':
  138. devid = int(os.getenv('DEVICE_ID'))
  139. context.set_context(device_id=devid)
  140. # init distributed
  141. if args.is_distributed:
  142. init()
  143. args.rank = get_rank()
  144. args.group_size = get_group_size()
  145. args.outputs_dir = os.path.join(args.log_path,
  146. datetime.datetime.now().strftime('%Y-%m-%d_time_%H_%M_%S'))
  147. args.logger = get_logger(args.outputs_dir, args.rank)
  148. args.logger.save_args(args)
  149. # network
  150. args.logger.important_info('start create network')
  151. if os.path.isdir(args.pretrained):
  152. models = list(glob.glob(os.path.join(args.pretrained, '*.ckpt')))
  153. f = lambda x: -1 * int(os.path.splitext(os.path.split(x)[-1])[0].split('-')[-1].split('_')[0])
  154. args.models = sorted(models, key=f)
  155. else:
  156. args.models = [args.pretrained,]
  157. for model in args.models:
  158. de_dataset = classification_dataset(args.data_dir, image_size=args.image_size,
  159. per_batch_size=args.per_batch_size,
  160. max_epoch=1, rank=args.rank, group_size=args.group_size,
  161. mode='eval')
  162. eval_dataloader = de_dataset.create_tuple_iterator()
  163. network = DenseNet121(args.num_classes)
  164. param_dict = load_checkpoint(model)
  165. param_dict_new = {}
  166. for key, values in param_dict.items():
  167. if key.startswith('moments.'):
  168. continue
  169. elif key.startswith('network.'):
  170. param_dict_new[key[8:]] = values
  171. else:
  172. param_dict_new[key] = values
  173. load_param_into_net(network, param_dict_new)
  174. args.logger.info('load model {} success'.format(model))
  175. if args.device_target == 'Ascend':
  176. network.add_flags_recursive(fp16=True)
  177. img_tot = 0
  178. top1_correct = 0
  179. top5_correct = 0
  180. network.set_train(False)
  181. for data, gt_classes in eval_dataloader:
  182. output = network(Tensor(data, mstype.float32))
  183. output = output.asnumpy()
  184. gt_classes = gt_classes.asnumpy()
  185. top1_output = np.argmax(output, (-1))
  186. top5_output = np.argsort(output)[:, -5:]
  187. t1_correct = np.equal(top1_output, gt_classes).sum()
  188. top1_correct += t1_correct
  189. top5_correct += get_top5_acc(top5_output, gt_classes)
  190. img_tot += args.per_batch_size
  191. results = [[top1_correct], [top5_correct], [img_tot]]
  192. args.logger.info('before results={}'.format(results))
  193. if args.is_distributed:
  194. results = generate_results(model, args.rank, args.group_size, top1_correct,
  195. top5_correct, img_tot)
  196. results = np.array(results)
  197. else:
  198. results = np.array(results)
  199. args.logger.info('after results={}'.format(results))
  200. top1_correct = results[0, 0]
  201. top5_correct = results[1, 0]
  202. img_tot = results[2, 0]
  203. acc1 = 100.0 * top1_correct / img_tot
  204. acc5 = 100.0 * top5_correct / img_tot
  205. args.logger.info('after allreduce eval: top1_correct={}, tot={}, acc={:.2f}%'.format(top1_correct,
  206. img_tot,
  207. acc1))
  208. args.logger.info('after allreduce eval: top5_correct={}, tot={}, acc={:.2f}%'.format(top5_correct,
  209. img_tot,
  210. acc5))
  211. if args.is_distributed:
  212. release()
  213. if __name__ == "__main__":
  214. test()