eval.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. # Copyright (c) 2019 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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import os
  18. import sys
  19. # add python path of PadleDetection to sys.path
  20. parent_path = os.path.abspath(os.path.join(__file__, *(['..'] * 2)))
  21. if parent_path not in sys.path:
  22. sys.path.append(parent_path)
  23. import paddle.fluid as fluid
  24. import logging
  25. FORMAT = '%(asctime)s-%(levelname)s: %(message)s'
  26. logging.basicConfig(level=logging.INFO, format=FORMAT)
  27. logger = logging.getLogger(__name__)
  28. try:
  29. from ppdet.utils.eval_utils import parse_fetches, eval_run, eval_results, json_eval_results
  30. import ppdet.utils.checkpoint as checkpoint
  31. from ppdet.utils.check import check_gpu, check_xpu, check_npu, check_version, check_config, enable_static_mode
  32. from ppdet.data.reader import create_reader
  33. from ppdet.core.workspace import load_config, merge_config, create
  34. from ppdet.utils.cli import ArgsParser
  35. except ImportError as e:
  36. if sys.argv[0].find('static') >= 0:
  37. logger.error("Importing ppdet failed when running static model "
  38. "with error: {}\n"
  39. "please try:\n"
  40. "\t1. run static model under PaddleDetection/static "
  41. "directory\n"
  42. "\t2. run 'pip uninstall ppdet' to uninstall ppdet "
  43. "dynamic version firstly.".format(e))
  44. sys.exit(-1)
  45. else:
  46. raise e
  47. def main():
  48. """
  49. Main evaluate function
  50. """
  51. env = os.environ
  52. cfg = load_config(FLAGS.config)
  53. merge_config(FLAGS.opt)
  54. check_config(cfg)
  55. # check if set use_gpu=True in paddlepaddle cpu version
  56. check_gpu(cfg.use_gpu)
  57. # disable npu in config by default and check use_npu
  58. if 'use_npu' not in cfg:
  59. cfg.use_npu = False
  60. check_npu(cfg.use_npu)
  61. use_xpu = False
  62. if hasattr(cfg, 'use_xpu'):
  63. check_xpu(cfg.use_xpu)
  64. use_xpu = cfg.use_xpu
  65. # check if paddlepaddle version is satisfied
  66. check_version()
  67. assert not (use_xpu and cfg.use_gpu), \
  68. 'Can not run on both XPU and GPU'
  69. assert not (cfg.use_npu and cfg.use_gpu), \
  70. 'Can not run on both NPU and GPU'
  71. main_arch = cfg.architecture
  72. multi_scale_test = getattr(cfg, 'MultiScaleTEST', None)
  73. if cfg.use_gpu and 'FLAGS_selected_gpus' in env:
  74. device_id = int(env['FLAGS_selected_gpus'])
  75. elif cfg.use_npu and 'FLAGS_selected_npus' in env:
  76. device_id = int(env['FLAGS_selected_npus'])
  77. elif use_xpu and 'FLAGS_selected_xpus' in env:
  78. device_id = int(env['FLAGS_selected_xpus'])
  79. else:
  80. device_id = 0
  81. # define executor
  82. if cfg.use_gpu:
  83. place = fluid.CUDAPlace(device_id)
  84. elif cfg.use_npu:
  85. place = fluid.NPUPlace(device_id)
  86. elif use_xpu:
  87. place = fluid.XPUPlace(device_id)
  88. else:
  89. place = fluid.CPUPlace()
  90. exe = fluid.Executor(place)
  91. # build program
  92. model = create(main_arch)
  93. startup_prog = fluid.Program()
  94. eval_prog = fluid.Program()
  95. with fluid.program_guard(eval_prog, startup_prog):
  96. with fluid.unique_name.guard():
  97. inputs_def = cfg['EvalReader']['inputs_def']
  98. feed_vars, loader = model.build_inputs(**inputs_def)
  99. if multi_scale_test is None:
  100. fetches = model.eval(feed_vars)
  101. else:
  102. fetches = model.eval(feed_vars, multi_scale_test)
  103. eval_prog = eval_prog.clone(True)
  104. reader = create_reader(cfg.EvalReader, devices_num=1)
  105. # When iterable mode, set set_sample_list_generator(reader, place)
  106. loader.set_sample_list_generator(reader)
  107. dataset = cfg['EvalReader']['dataset']
  108. # eval already exists json file
  109. if FLAGS.json_eval:
  110. logger.info(
  111. "In json_eval mode, PaddleDetection will evaluate json files in "
  112. "output_eval directly. And proposal.json, bbox.json and mask.json "
  113. "will be detected by default.")
  114. json_eval_results(
  115. cfg.metric, json_directory=FLAGS.output_eval, dataset=dataset)
  116. return
  117. compile_program = fluid.CompiledProgram(eval_prog).with_data_parallel()
  118. if use_xpu or cfg.use_npu:
  119. compile_program = eval_prog
  120. assert cfg.metric != 'OID', "eval process of OID dataset \
  121. is not supported."
  122. if cfg.metric == "WIDERFACE":
  123. raise ValueError("metric type {} does not support in tools/eval.py, "
  124. "please use tools/face_eval.py".format(cfg.metric))
  125. assert cfg.metric in ['COCO', 'VOC'], \
  126. "unknown metric type {}".format(cfg.metric)
  127. extra_keys = []
  128. if cfg.metric == 'COCO':
  129. extra_keys = ['im_info', 'im_id', 'im_shape']
  130. if cfg.metric == 'VOC':
  131. extra_keys = ['gt_bbox', 'gt_class', 'is_difficult']
  132. keys, values, cls = parse_fetches(fetches, eval_prog, extra_keys)
  133. # whether output bbox is normalized in model output layer
  134. is_bbox_normalized = False
  135. if hasattr(model, 'is_bbox_normalized') and \
  136. callable(model.is_bbox_normalized):
  137. is_bbox_normalized = model.is_bbox_normalized()
  138. sub_eval_prog = None
  139. sub_keys = None
  140. sub_values = None
  141. # build sub-program
  142. if 'Mask' in main_arch and multi_scale_test:
  143. sub_eval_prog = fluid.Program()
  144. with fluid.program_guard(sub_eval_prog, startup_prog):
  145. with fluid.unique_name.guard():
  146. inputs_def = cfg['EvalReader']['inputs_def']
  147. inputs_def['mask_branch'] = True
  148. feed_vars, eval_loader = model.build_inputs(**inputs_def)
  149. sub_fetches = model.eval(
  150. feed_vars, multi_scale_test, mask_branch=True)
  151. assert cfg.metric == 'COCO'
  152. extra_keys = ['im_id', 'im_shape']
  153. sub_keys, sub_values, _ = parse_fetches(sub_fetches, sub_eval_prog,
  154. extra_keys)
  155. sub_eval_prog = sub_eval_prog.clone(True)
  156. # load model
  157. exe.run(startup_prog)
  158. if 'weights' in cfg:
  159. checkpoint.load_params(exe, startup_prog, cfg.weights)
  160. resolution = None
  161. if 'Mask' in cfg.architecture or cfg.architecture == 'HybridTaskCascade':
  162. resolution = model.mask_head.resolution
  163. results = eval_run(exe, compile_program, loader, keys, values, cls, cfg,
  164. sub_eval_prog, sub_keys, sub_values, resolution)
  165. # evaluation
  166. # if map_type not set, use default 11point, only use in VOC eval
  167. map_type = cfg.map_type if 'map_type' in cfg else '11point'
  168. save_only = getattr(cfg, 'save_prediction_only', False)
  169. eval_results(
  170. results,
  171. cfg.metric,
  172. cfg.num_classes,
  173. resolution,
  174. is_bbox_normalized,
  175. FLAGS.output_eval,
  176. map_type,
  177. dataset=dataset,
  178. save_only=save_only)
  179. if __name__ == '__main__':
  180. enable_static_mode()
  181. parser = ArgsParser()
  182. parser.add_argument(
  183. "--json_eval",
  184. action='store_true',
  185. default=False,
  186. help="Whether to re eval with already exists bbox.json or mask.json")
  187. parser.add_argument(
  188. "-f",
  189. "--output_eval",
  190. default=None,
  191. type=str,
  192. help="Evaluation file directory, default is current directory.")
  193. FLAGS = parser.parse_args()
  194. main()