eval.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  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. import os
  15. import sys
  16. import numpy as np
  17. import argparse
  18. import paddle
  19. from ppdet.core.workspace import load_config, merge_config
  20. from ppdet.core.workspace import create
  21. from ppdet.metrics import COCOMetric, VOCMetric, KeyPointTopDownCOCOEval
  22. from paddleslim.auto_compression.config_helpers import load_config as load_slim_config
  23. from post_process import PPYOLOEPostProcess
  24. def argsparser():
  25. parser = argparse.ArgumentParser(description=__doc__)
  26. parser.add_argument(
  27. '--config_path',
  28. type=str,
  29. default=None,
  30. help="path of compression strategy config.",
  31. required=True)
  32. parser.add_argument(
  33. '--devices',
  34. type=str,
  35. default='gpu',
  36. help="which device used to compress.")
  37. return parser
  38. def reader_wrapper(reader, input_list):
  39. def gen():
  40. for data in reader:
  41. in_dict = {}
  42. if isinstance(input_list, list):
  43. for input_name in input_list:
  44. in_dict[input_name] = data[input_name]
  45. elif isinstance(input_list, dict):
  46. for input_name in input_list.keys():
  47. in_dict[input_list[input_name]] = data[input_name]
  48. yield in_dict
  49. return gen
  50. def convert_numpy_data(data, metric):
  51. data_all = {}
  52. data_all = {k: np.array(v) for k, v in data.items()}
  53. if isinstance(metric, VOCMetric):
  54. for k, v in data_all.items():
  55. if not isinstance(v[0], np.ndarray):
  56. tmp_list = []
  57. for t in v:
  58. tmp_list.append(np.array(t))
  59. data_all[k] = np.array(tmp_list)
  60. else:
  61. data_all = {k: np.array(v) for k, v in data.items()}
  62. return data_all
  63. def eval():
  64. place = paddle.CUDAPlace(0) if FLAGS.devices == 'gpu' else paddle.CPUPlace()
  65. exe = paddle.static.Executor(place)
  66. val_program, feed_target_names, fetch_targets = paddle.static.load_inference_model(
  67. global_config["model_dir"].rstrip('/'),
  68. exe,
  69. model_filename=global_config["model_filename"],
  70. params_filename=global_config["params_filename"])
  71. print('Loaded model from: {}'.format(global_config["model_dir"]))
  72. metric = global_config['metric']
  73. for batch_id, data in enumerate(val_loader):
  74. data_all = convert_numpy_data(data, metric)
  75. data_input = {}
  76. for k, v in data.items():
  77. if isinstance(global_config['input_list'], list):
  78. if k in global_config['input_list']:
  79. data_input[k] = np.array(v)
  80. elif isinstance(global_config['input_list'], dict):
  81. if k in global_config['input_list'].keys():
  82. data_input[global_config['input_list'][k]] = np.array(v)
  83. outs = exe.run(val_program,
  84. feed=data_input,
  85. fetch_list=fetch_targets,
  86. return_numpy=False)
  87. res = {}
  88. if 'arch' in global_config and global_config['arch'] == 'PPYOLOE':
  89. postprocess = PPYOLOEPostProcess(
  90. score_threshold=0.01, nms_threshold=0.6)
  91. res = postprocess(np.array(outs[0]), data_all['scale_factor'])
  92. else:
  93. for out in outs:
  94. v = np.array(out)
  95. if len(v.shape) > 1:
  96. res['bbox'] = v
  97. else:
  98. res['bbox_num'] = v
  99. metric.update(data_all, res)
  100. if batch_id % 100 == 0:
  101. print('Eval iter:', batch_id)
  102. metric.accumulate()
  103. metric.log()
  104. metric.reset()
  105. def main():
  106. global global_config
  107. all_config = load_slim_config(FLAGS.config_path)
  108. assert "Global" in all_config, "Key 'Global' not found in config file."
  109. global_config = all_config["Global"]
  110. reader_cfg = load_config(global_config['reader_config'])
  111. dataset = reader_cfg['EvalDataset']
  112. global val_loader
  113. val_loader = create('EvalReader')(reader_cfg['EvalDataset'],
  114. reader_cfg['worker_num'],
  115. return_list=True)
  116. metric = None
  117. if reader_cfg['metric'] == 'COCO':
  118. clsid2catid = {v: k for k, v in dataset.catid2clsid.items()}
  119. anno_file = dataset.get_anno()
  120. metric = COCOMetric(
  121. anno_file=anno_file, clsid2catid=clsid2catid, IouType='bbox')
  122. elif reader_cfg['metric'] == 'VOC':
  123. metric = VOCMetric(
  124. label_list=dataset.get_label_list(),
  125. class_num=reader_cfg['num_classes'],
  126. map_type=reader_cfg['map_type'])
  127. elif reader_cfg['metric'] == 'KeyPointTopDownCOCOEval':
  128. anno_file = dataset.get_anno()
  129. metric = KeyPointTopDownCOCOEval(anno_file,
  130. len(dataset), 17, 'output_eval')
  131. else:
  132. raise ValueError("metric currently only supports COCO and VOC.")
  133. global_config['metric'] = metric
  134. eval()
  135. if __name__ == '__main__':
  136. paddle.enable_static()
  137. parser = argsparser()
  138. FLAGS = parser.parse_args()
  139. assert FLAGS.devices in ['cpu', 'gpu', 'xpu', 'npu']
  140. paddle.set_device(FLAGS.devices)
  141. main()