eval.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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__, *(['..'] * 3)))
  21. if parent_path not in sys.path:
  22. sys.path.append(parent_path)
  23. import paddle.fluid as fluid
  24. from paddleslim.prune import Pruner
  25. from paddleslim.analysis import flops
  26. import logging
  27. FORMAT = '%(asctime)s-%(levelname)s: %(message)s'
  28. logging.basicConfig(level=logging.INFO, format=FORMAT)
  29. logger = logging.getLogger(__name__)
  30. try:
  31. from ppdet.utils.eval_utils import parse_fetches, eval_run, eval_results, json_eval_results
  32. import ppdet.utils.checkpoint as checkpoint
  33. from ppdet.utils.check import check_gpu, check_version, check_config, enable_static_mode
  34. from ppdet.data.reader import create_reader
  35. from ppdet.core.workspace import load_config, merge_config, create
  36. from ppdet.utils.cli import ArgsParser
  37. except ImportError as e:
  38. if sys.argv[0].find('static') >= 0:
  39. logger.error("Importing ppdet failed when running static model "
  40. "with error: {}\n"
  41. "please try:\n"
  42. "\t1. run static model under PaddleDetection/static "
  43. "directory\n"
  44. "\t2. run 'pip uninstall ppdet' to uninstall ppdet "
  45. "dynamic version firstly.".format(e))
  46. sys.exit(-1)
  47. else:
  48. raise e
  49. def main():
  50. """
  51. Main evaluate function
  52. """
  53. cfg = load_config(FLAGS.config)
  54. merge_config(FLAGS.opt)
  55. check_config(cfg)
  56. # check if set use_gpu=True in paddlepaddle cpu version
  57. check_gpu(cfg.use_gpu)
  58. # check if paddlepaddle version is satisfied
  59. check_version()
  60. main_arch = cfg.architecture
  61. multi_scale_test = getattr(cfg, 'MultiScaleTEST', None)
  62. # define executor
  63. place = fluid.CUDAPlace(0) if cfg.use_gpu else fluid.CPUPlace()
  64. exe = fluid.Executor(place)
  65. # build program
  66. model = create(main_arch)
  67. startup_prog = fluid.Program()
  68. eval_prog = fluid.Program()
  69. with fluid.program_guard(eval_prog, startup_prog):
  70. with fluid.unique_name.guard():
  71. inputs_def = cfg['EvalReader']['inputs_def']
  72. feed_vars, loader = model.build_inputs(**inputs_def)
  73. if multi_scale_test is None:
  74. fetches = model.eval(feed_vars)
  75. else:
  76. fetches = model.eval(feed_vars, multi_scale_test)
  77. eval_prog = eval_prog.clone(True)
  78. exe.run(startup_prog)
  79. reader = create_reader(cfg.EvalReader)
  80. # When iterable mode, set set_sample_list_generator(reader, place)
  81. loader.set_sample_list_generator(reader)
  82. dataset = cfg['EvalReader']['dataset']
  83. # eval already exists json file
  84. if FLAGS.json_eval:
  85. logger.info(
  86. "In json_eval mode, PaddleDetection will evaluate json files in "
  87. "output_eval directly. And proposal.json, bbox.json and mask.json "
  88. "will be detected by default.")
  89. json_eval_results(
  90. cfg.metric, json_directory=FLAGS.output_eval, dataset=dataset)
  91. return
  92. pruned_params = FLAGS.pruned_params
  93. assert (
  94. FLAGS.pruned_params is not None
  95. ), "FLAGS.pruned_params is empty!!! Please set it by '--pruned_params' option."
  96. pruned_params = FLAGS.pruned_params.strip().split(",")
  97. logger.info("pruned params: {}".format(pruned_params))
  98. pruned_ratios = [float(n) for n in FLAGS.pruned_ratios.strip().split(",")]
  99. logger.info("pruned ratios: {}".format(pruned_ratios))
  100. assert (len(pruned_params) == len(pruned_ratios)
  101. ), "The length of pruned params and pruned ratios should be equal."
  102. assert (pruned_ratios > [0] * len(pruned_ratios) and
  103. pruned_ratios < [1] * len(pruned_ratios)
  104. ), "The elements of pruned ratios should be in range (0, 1)."
  105. base_flops = flops(eval_prog)
  106. pruner = Pruner()
  107. eval_prog, _, _ = pruner.prune(
  108. eval_prog,
  109. fluid.global_scope(),
  110. params=pruned_params,
  111. ratios=pruned_ratios,
  112. place=place,
  113. only_graph=False)
  114. pruned_flops = flops(eval_prog)
  115. logger.info("pruned FLOPS: {}".format(
  116. float(base_flops - pruned_flops) / base_flops))
  117. compile_program = fluid.CompiledProgram(eval_prog).with_data_parallel()
  118. assert cfg.metric != 'OID', "eval process of OID dataset \
  119. is not supported."
  120. if cfg.metric == "WIDERFACE":
  121. raise ValueError("metric type {} does not support in tools/eval.py, "
  122. "please use tools/face_eval.py".format(cfg.metric))
  123. assert cfg.metric in ['COCO', 'VOC'], \
  124. "unknown metric type {}".format(cfg.metric)
  125. extra_keys = []
  126. if cfg.metric == 'COCO':
  127. extra_keys = ['im_info', 'im_id', 'im_shape']
  128. if cfg.metric == 'VOC':
  129. extra_keys = ['gt_bbox', 'gt_class', 'is_difficult']
  130. keys, values, cls = parse_fetches(fetches, eval_prog, extra_keys)
  131. # whether output bbox is normalized in model output layer
  132. is_bbox_normalized = False
  133. if hasattr(model, 'is_bbox_normalized') and \
  134. callable(model.is_bbox_normalized):
  135. is_bbox_normalized = model.is_bbox_normalized()
  136. sub_eval_prog = None
  137. sub_keys = None
  138. sub_values = None
  139. # build sub-program
  140. if 'Mask' in main_arch and multi_scale_test:
  141. sub_eval_prog = fluid.Program()
  142. with fluid.program_guard(sub_eval_prog, startup_prog):
  143. with fluid.unique_name.guard():
  144. inputs_def = cfg['EvalReader']['inputs_def']
  145. inputs_def['mask_branch'] = True
  146. feed_vars, eval_loader = model.build_inputs(**inputs_def)
  147. sub_fetches = model.eval(
  148. feed_vars, multi_scale_test, mask_branch=True)
  149. assert cfg.metric == 'COCO'
  150. extra_keys = ['im_id', 'im_shape']
  151. sub_keys, sub_values, _ = parse_fetches(sub_fetches, sub_eval_prog,
  152. extra_keys)
  153. sub_eval_prog = sub_eval_prog.clone(True)
  154. # load model
  155. if 'weights' in cfg:
  156. checkpoint.load_checkpoint(exe, eval_prog, cfg.weights)
  157. resolution = None
  158. if 'Mask' in cfg.architecture:
  159. resolution = model.mask_head.resolution
  160. results = eval_run(
  161. exe,
  162. compile_program,
  163. loader,
  164. keys,
  165. values,
  166. cls,
  167. cfg,
  168. sub_eval_prog,
  169. sub_keys,
  170. sub_values,
  171. resolution=resolution)
  172. # if map_type not set, use default 11point, only use in VOC eval
  173. map_type = cfg.map_type if 'map_type' in cfg else '11point'
  174. eval_results(
  175. results,
  176. cfg.metric,
  177. cfg.num_classes,
  178. resolution,
  179. is_bbox_normalized,
  180. FLAGS.output_eval,
  181. map_type,
  182. dataset=dataset)
  183. if __name__ == '__main__':
  184. enable_static_mode()
  185. parser = ArgsParser()
  186. parser.add_argument(
  187. "--json_eval",
  188. action='store_true',
  189. default=False,
  190. help="Whether to re eval with already exists bbox.json or mask.json")
  191. parser.add_argument(
  192. "-f",
  193. "--output_eval",
  194. default=None,
  195. type=str,
  196. help="Evaluation file directory, default is current directory.")
  197. parser.add_argument(
  198. "-p",
  199. "--pruned_params",
  200. default=None,
  201. type=str,
  202. help="The parameters to be pruned when calculating sensitivities.")
  203. parser.add_argument(
  204. "--pruned_ratios",
  205. default=None,
  206. type=str,
  207. help="The ratios pruned iteratively for each parameter when calculating sensitivities."
  208. )
  209. FLAGS = parser.parse_args()
  210. main()