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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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='GPU', 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="imagenet2012")
  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('--pretrained', 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. # roma obs
  63. parser.add_argument('--train_url', type=str, default="", help='train url')
  64. args_opt = parser.parse_args()
  65. args_opt = merge_args(args_opt, cloud_args)
  66. if args_opt.dataset == "cifar10":
  67. from src.config import cifar_cfg as cfg
  68. else:
  69. from src.config import imagenet_cfg as cfg
  70. args_opt.image_size = cfg.image_size
  71. args_opt.num_classes = cfg.num_classes
  72. args_opt.per_batch_size = cfg.batch_size
  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.image_size = list(map(int, args_opt.image_size.split(',')))
  79. return args_opt
  80. def get_top5_acc(top5_arg, gt_class):
  81. sub_count = 0
  82. for top5, gt in zip(top5_arg, gt_class):
  83. if gt in top5:
  84. sub_count += 1
  85. return sub_count
  86. def merge_args(args, cloud_args):
  87. """merge_args"""
  88. args_dict = vars(args)
  89. if isinstance(cloud_args, dict):
  90. for key in cloud_args.keys():
  91. val = cloud_args[key]
  92. if key in args_dict and val:
  93. arg_type = type(args_dict[key])
  94. if arg_type is not type(None):
  95. val = arg_type(val)
  96. args_dict[key] = val
  97. return args
  98. def test(cloud_args=None):
  99. """test"""
  100. args = parse_args(cloud_args)
  101. context.set_context(mode=context.GRAPH_MODE, enable_auto_mixed_precision=True,
  102. device_target=args.device_target, save_graphs=False)
  103. if os.getenv('DEVICE_ID', "not_set").isdigit():
  104. context.set_context(device_id=int(os.getenv('DEVICE_ID')))
  105. args.outputs_dir = os.path.join(args.log_path,
  106. datetime.datetime.now().strftime('%Y-%m-%d_time_%H_%M_%S'))
  107. args.logger = get_logger(args.outputs_dir, args.rank)
  108. args.logger.save_args(args)
  109. if args.dataset == "cifar10":
  110. net = vgg16(num_classes=args.num_classes)
  111. opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), 0.01, cfg.momentum,
  112. weight_decay=args.weight_decay)
  113. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean', is_grad=False)
  114. model = Model(net, loss_fn=loss, optimizer=opt, metrics={'acc'})
  115. param_dict = load_checkpoint(args.checkpoint_path)
  116. load_param_into_net(net, param_dict)
  117. net.set_train(False)
  118. dataset = vgg_create_dataset(args.data_path, 1, False)
  119. res = model.eval(dataset)
  120. print("result: ", res)
  121. else:
  122. # network
  123. args.logger.important_info('start create network')
  124. if os.path.isdir(args.pretrained):
  125. models = list(glob.glob(os.path.join(args.pretrained, '*.ckpt')))
  126. print(models)
  127. if args.graph_ckpt:
  128. f = lambda x: -1 * int(os.path.splitext(os.path.split(x)[-1])[0].split('-')[-1].split('_')[0])
  129. else:
  130. f = lambda x: -1 * int(os.path.splitext(os.path.split(x)[-1])[0].split('_')[-1])
  131. args.models = sorted(models, key=f)
  132. else:
  133. args.models = [args.pretrained,]
  134. for model in args.models:
  135. if args.dataset == "cifar10":
  136. dataset = vgg_create_dataset(args.data_path, args.image_size, args.per_batch_size, training=False)
  137. else:
  138. dataset = classification_dataset(args.data_path, args.image_size, args.per_batch_size)
  139. eval_dataloader = dataset.create_tuple_iterator()
  140. network = vgg16(args.num_classes, args, phase="test")
  141. # pre_trained
  142. load_param_into_net(network, load_checkpoint(model))
  143. network.add_flags_recursive(fp16=True)
  144. img_tot = 0
  145. top1_correct = 0
  146. top5_correct = 0
  147. network.set_train(False)
  148. t_end = time.time()
  149. it = 0
  150. for data, gt_classes in eval_dataloader:
  151. output = network(Tensor(data, mstype.float32))
  152. output = output.asnumpy()
  153. top1_output = np.argmax(output, (-1))
  154. top5_output = np.argsort(output)[:, -5:]
  155. t1_correct = np.equal(top1_output, gt_classes).sum()
  156. top1_correct += t1_correct
  157. top5_correct += get_top5_acc(top5_output, gt_classes)
  158. img_tot += args.per_batch_size
  159. if args.rank == 0 and it == 0:
  160. t_end = time.time()
  161. it = 1
  162. if args.rank == 0:
  163. time_used = time.time() - t_end
  164. fps = (img_tot - args.per_batch_size) * args.group_size / time_used
  165. args.logger.info('Inference Performance: {:.2f} img/sec'.format(fps))
  166. results = [[top1_correct], [top5_correct], [img_tot]]
  167. args.logger.info('before results={}'.format(results))
  168. results = np.array(results)
  169. args.logger.info('after results={}'.format(results))
  170. top1_correct = results[0, 0]
  171. top5_correct = results[1, 0]
  172. img_tot = results[2, 0]
  173. acc1 = 100.0 * top1_correct / img_tot
  174. acc5 = 100.0 * top5_correct / img_tot
  175. args.logger.info('after allreduce eval: top1_correct={}, tot={},'
  176. 'acc={:.2f}%(TOP1)'.format(top1_correct, img_tot, acc1))
  177. args.logger.info('after allreduce eval: top5_correct={}, tot={},'
  178. 'acc={:.2f}%(TOP5)'.format(top5_correct, img_tot, acc5))
  179. if __name__ == "__main__":
  180. test()