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.6 kB

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