sensitive.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. from paddle import fluid
  24. from ppdet.core.workspace import load_config, merge_config, create
  25. from ppdet.data.reader import create_reader
  26. from ppdet.utils.eval_utils import parse_fetches, eval_run, eval_results
  27. from ppdet.utils.cli import ArgsParser
  28. from ppdet.utils.check import check_version, check_config, enable_static_mode
  29. import ppdet.utils.checkpoint as checkpoint
  30. from paddleslim.prune import sensitivity
  31. import logging
  32. FORMAT = '%(asctime)s-%(levelname)s: %(message)s'
  33. logging.basicConfig(level=logging.INFO, format=FORMAT)
  34. logger = logging.getLogger(__name__)
  35. def main():
  36. env = os.environ
  37. print("FLAGS.config: {}".format(FLAGS.config))
  38. cfg = load_config(FLAGS.config)
  39. merge_config(FLAGS.opt)
  40. check_config(cfg)
  41. check_version()
  42. main_arch = cfg.architecture
  43. place = fluid.CUDAPlace(0)
  44. exe = fluid.Executor(place)
  45. # build program
  46. startup_prog = fluid.Program()
  47. eval_prog = fluid.Program()
  48. with fluid.program_guard(eval_prog, startup_prog):
  49. with fluid.unique_name.guard():
  50. model = create(main_arch)
  51. inputs_def = cfg['EvalReader']['inputs_def']
  52. feed_vars, eval_loader = model.build_inputs(**inputs_def)
  53. fetches = model.eval(feed_vars)
  54. eval_prog = eval_prog.clone(True)
  55. if FLAGS.print_params:
  56. print(
  57. "-------------------------All parameters in current graph----------------------"
  58. )
  59. for block in eval_prog.blocks:
  60. for param in block.all_parameters():
  61. print("parameter name: {}\tshape: {}".format(param.name,
  62. param.shape))
  63. print(
  64. "------------------------------------------------------------------------------"
  65. )
  66. return
  67. eval_reader = create_reader(cfg.EvalReader)
  68. # When iterable mode, set set_sample_list_generator(eval_reader, place)
  69. eval_loader.set_sample_list_generator(eval_reader)
  70. # parse eval fetches
  71. extra_keys = []
  72. if cfg.metric == 'COCO':
  73. extra_keys = ['im_info', 'im_id', 'im_shape']
  74. if cfg.metric == 'VOC':
  75. extra_keys = ['gt_bbox', 'gt_class', 'is_difficult']
  76. if cfg.metric == 'WIDERFACE':
  77. extra_keys = ['im_id', 'im_shape', 'gt_box']
  78. eval_keys, eval_values, eval_cls = parse_fetches(fetches, eval_prog,
  79. extra_keys)
  80. exe.run(startup_prog)
  81. fuse_bn = getattr(model.backbone, 'norm_type', None) == 'affine_channel'
  82. ignore_params = cfg.finetune_exclude_pretrained_params \
  83. if 'finetune_exclude_pretrained_params' in cfg else []
  84. start_iter = 0
  85. if cfg.weights:
  86. checkpoint.load_params(exe, eval_prog, cfg.weights)
  87. else:
  88. logger.warning("Please set cfg.weights to load trained model.")
  89. # whether output bbox is normalized in model output layer
  90. is_bbox_normalized = False
  91. if hasattr(model, 'is_bbox_normalized') and \
  92. callable(model.is_bbox_normalized):
  93. is_bbox_normalized = model.is_bbox_normalized()
  94. # if map_type not set, use default 11point, only use in VOC eval
  95. map_type = cfg.map_type if 'map_type' in cfg else '11point'
  96. def test(program):
  97. compiled_eval_prog = fluid.CompiledProgram(program)
  98. results = eval_run(
  99. exe,
  100. compiled_eval_prog,
  101. eval_loader,
  102. eval_keys,
  103. eval_values,
  104. eval_cls,
  105. cfg=cfg)
  106. resolution = None
  107. if 'mask' in results[0]:
  108. resolution = model.mask_head.resolution
  109. dataset = cfg['EvalReader']['dataset']
  110. box_ap_stats = eval_results(
  111. results,
  112. cfg.metric,
  113. cfg.num_classes,
  114. resolution,
  115. is_bbox_normalized,
  116. FLAGS.output_eval,
  117. map_type,
  118. dataset=dataset)
  119. return box_ap_stats[0]
  120. pruned_params = FLAGS.pruned_params
  121. assert (
  122. FLAGS.pruned_params is not None
  123. ), "FLAGS.pruned_params is empty!!! Please set it by '--pruned_params' option."
  124. pruned_params = FLAGS.pruned_params.strip().split(",")
  125. logger.info("pruned params: {}".format(pruned_params))
  126. pruned_ratios = [float(n) for n in FLAGS.pruned_ratios.strip().split(" ")]
  127. logger.info("pruned ratios: {}".format(pruned_ratios))
  128. sensitivity(
  129. eval_prog,
  130. place,
  131. pruned_params,
  132. test,
  133. sensitivities_file=FLAGS.sensitivities_file,
  134. pruned_ratios=pruned_ratios)
  135. if __name__ == '__main__':
  136. enable_static_mode()
  137. parser = ArgsParser()
  138. parser.add_argument(
  139. "--output_eval",
  140. default=None,
  141. type=str,
  142. help="Evaluation directory, default is current directory.")
  143. parser.add_argument(
  144. "-d",
  145. "--dataset_dir",
  146. default=None,
  147. type=str,
  148. help="Dataset path, same as DataFeed.dataset.dataset_dir")
  149. parser.add_argument(
  150. "-s",
  151. "--sensitivities_file",
  152. default="sensitivities.data",
  153. type=str,
  154. help="The file used to save sensitivities.")
  155. parser.add_argument(
  156. "-p",
  157. "--pruned_params",
  158. default=None,
  159. type=str,
  160. help="The parameters to be pruned when calculating sensitivities.")
  161. parser.add_argument(
  162. "-r",
  163. "--pruned_ratios",
  164. default="0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9",
  165. type=str,
  166. help="The ratios pruned iteratively for each parameter when calculating sensitivities."
  167. )
  168. parser.add_argument(
  169. "-P",
  170. "--print_params",
  171. default=False,
  172. action='store_true',
  173. help="Whether to only print the parameters' names and shapes.")
  174. FLAGS = parser.parse_args()
  175. main()