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

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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.nn.optim.momentum import Momentum
  25. from mindspore.train.model import Model
  26. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  27. from mindspore.ops import operations as P
  28. from mindspore.ops import functional as F
  29. from mindspore.common import dtype as mstype
  30. from src.utils.logging import get_logger
  31. from src.vgg import vgg16
  32. from src.dataset import vgg_create_dataset
  33. from src.dataset import classification_dataset
  34. class ParameterReduce(nn.Cell):
  35. """ParameterReduce"""
  36. def __init__(self):
  37. super(ParameterReduce, self).__init__()
  38. self.cast = P.Cast()
  39. self.reduce = P.AllReduce()
  40. def construct(self, x):
  41. one = self.cast(F.scalar_to_array(1.0), mstype.float32)
  42. out = x * one
  43. ret = self.reduce(out)
  44. return ret
  45. def parse_args(cloud_args=None):
  46. """parse_args"""
  47. parser = argparse.ArgumentParser('mindspore classification test')
  48. parser.add_argument('--device_target', type=str, default='Ascend', choices=['Ascend', 'GPU'],
  49. help='device where the code will be implemented. (Default: Ascend)')
  50. # dataset related
  51. parser.add_argument('--dataset', type=str, choices=["cifar10", "imagenet2012"], default="cifar10")
  52. parser.add_argument('--data_path', type=str, default='', help='eval data dir')
  53. parser.add_argument('--per_batch_size', default=32, type=int, help='batch size for per npu')
  54. # network related
  55. parser.add_argument('--graph_ckpt', type=int, default=1, help='graph ckpt or feed ckpt')
  56. parser.add_argument('--pre_trained', default='', type=str, help='fully path of pretrained model to load. '
  57. 'If it is a direction, it will test all ckpt')
  58. # logging related
  59. parser.add_argument('--log_path', type=str, default='outputs/', help='path to save log')
  60. parser.add_argument('--rank', type=int, default=0, help='local rank of distributed')
  61. parser.add_argument('--group_size', type=int, default=1, help='world size of distributed')
  62. args_opt = parser.parse_args()
  63. args_opt = merge_args(args_opt, cloud_args)
  64. if args_opt.dataset == "cifar10":
  65. from src.config import cifar_cfg as cfg
  66. else:
  67. from src.config import imagenet_cfg as cfg
  68. args_opt.image_size = cfg.image_size
  69. args_opt.num_classes = cfg.num_classes
  70. args_opt.per_batch_size = cfg.batch_size
  71. args_opt.momentum = cfg.momentum
  72. args_opt.weight_decay = cfg.weight_decay
  73. args_opt.buffer_size = cfg.buffer_size
  74. args_opt.pad_mode = cfg.pad_mode
  75. args_opt.padding = cfg.padding
  76. args_opt.has_bias = cfg.has_bias
  77. args_opt.batch_norm = cfg.batch_norm
  78. args_opt.initialize_mode = cfg.initialize_mode
  79. args_opt.has_dropout = cfg.has_dropout
  80. args_opt.image_size = list(map(int, args_opt.image_size.split(',')))
  81. return args_opt
  82. def get_top5_acc(top5_arg, gt_class):
  83. sub_count = 0
  84. for top5, gt in zip(top5_arg, gt_class):
  85. if gt in top5:
  86. sub_count += 1
  87. return sub_count
  88. def merge_args(args, cloud_args):
  89. """merge_args"""
  90. args_dict = vars(args)
  91. if isinstance(cloud_args, dict):
  92. for key in cloud_args.keys():
  93. val = cloud_args[key]
  94. if key in args_dict and val:
  95. arg_type = type(args_dict[key])
  96. if arg_type is not type(None):
  97. val = arg_type(val)
  98. args_dict[key] = val
  99. return args
  100. def test(cloud_args=None):
  101. """test"""
  102. args = parse_args(cloud_args)
  103. context.set_context(mode=context.GRAPH_MODE, enable_auto_mixed_precision=True,
  104. device_target=args.device_target, save_graphs=False)
  105. if os.getenv('DEVICE_ID', "not_set").isdigit():
  106. context.set_context(device_id=int(os.getenv('DEVICE_ID')))
  107. args.outputs_dir = os.path.join(args.log_path,
  108. datetime.datetime.now().strftime('%Y-%m-%d_time_%H_%M_%S'))
  109. args.logger = get_logger(args.outputs_dir, args.rank)
  110. args.logger.save_args(args)
  111. if args.dataset == "cifar10":
  112. net = vgg16(num_classes=args.num_classes, args=args)
  113. opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), 0.01, args.momentum,
  114. weight_decay=args.weight_decay)
  115. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean', is_grad=False)
  116. model = Model(net, loss_fn=loss, optimizer=opt, metrics={'acc'})
  117. param_dict = load_checkpoint(args.pre_trained)
  118. load_param_into_net(net, param_dict)
  119. net.set_train(False)
  120. dataset = vgg_create_dataset(args.data_path, args.image_size, args.per_batch_size, training=False)
  121. res = model.eval(dataset)
  122. print("result: ", res)
  123. else:
  124. # network
  125. args.logger.important_info('start create network')
  126. if os.path.isdir(args.pre_trained):
  127. models = list(glob.glob(os.path.join(args.pre_trained, '*.ckpt')))
  128. print(models)
  129. if args.graph_ckpt:
  130. f = lambda x: -1 * int(os.path.splitext(os.path.split(x)[-1])[0].split('-')[-1].split('_')[0])
  131. else:
  132. f = lambda x: -1 * int(os.path.splitext(os.path.split(x)[-1])[0].split('_')[-1])
  133. args.models = sorted(models, key=f)
  134. else:
  135. args.models = [args.pre_trained,]
  136. for model in args.models:
  137. dataset = classification_dataset(args.data_path, args.image_size, args.per_batch_size, mode='eval')
  138. eval_dataloader = dataset.create_tuple_iterator()
  139. network = vgg16(args.num_classes, args, phase="test")
  140. # pre_trained
  141. load_param_into_net(network, load_checkpoint(model))
  142. network.add_flags_recursive(fp16=True)
  143. img_tot = 0
  144. top1_correct = 0
  145. top5_correct = 0
  146. network.set_train(False)
  147. t_end = time.time()
  148. it = 0
  149. for data, gt_classes in eval_dataloader:
  150. output = network(Tensor(data, mstype.float32))
  151. output = output.asnumpy()
  152. top1_output = np.argmax(output, (-1))
  153. top5_output = np.argsort(output)[:, -5:]
  154. t1_correct = np.equal(top1_output, gt_classes).sum()
  155. top1_correct += t1_correct
  156. top5_correct += get_top5_acc(top5_output, gt_classes)
  157. img_tot += args.per_batch_size
  158. if args.rank == 0 and it == 0:
  159. t_end = time.time()
  160. it = 1
  161. if args.rank == 0:
  162. time_used = time.time() - t_end
  163. fps = (img_tot - args.per_batch_size) * args.group_size / time_used
  164. args.logger.info('Inference Performance: {:.2f} img/sec'.format(fps))
  165. results = [[top1_correct], [top5_correct], [img_tot]]
  166. args.logger.info('before results={}'.format(results))
  167. results = np.array(results)
  168. args.logger.info('after results={}'.format(results))
  169. top1_correct = results[0, 0]
  170. top5_correct = results[1, 0]
  171. img_tot = results[2, 0]
  172. acc1 = 100.0 * top1_correct / img_tot
  173. acc5 = 100.0 * top5_correct / img_tot
  174. args.logger.info('after allreduce eval: top1_correct={}, tot={},'
  175. 'acc={:.2f}%(TOP1)'.format(top1_correct, img_tot, acc1))
  176. args.logger.info('after allreduce eval: top5_correct={}, tot={},'
  177. 'acc={:.2f}%(TOP5)'.format(top5_correct, img_tot, acc5))
  178. if __name__ == "__main__":
  179. test()