export_model.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. # Copyright (c) 2020 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. 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.core.workspace import load_config, merge_config, create
  30. from ppdet.utils.cli import ArgsParser
  31. import ppdet.utils.checkpoint as checkpoint
  32. from ppdet.utils.export_utils import save_infer_model, dump_infer_config
  33. from ppdet.utils.check import check_config, check_version, enable_static_mode
  34. except ImportError as e:
  35. if sys.argv[0].find('static') >= 0:
  36. logger.error("Importing ppdet failed when running static model "
  37. "with error: {}\n"
  38. "please try:\n"
  39. "\t1. run static model under PaddleDetection/static "
  40. "directory\n"
  41. "\t2. run 'pip uninstall ppdet' to uninstall ppdet "
  42. "dynamic version firstly.".format(e))
  43. sys.exit(-1)
  44. else:
  45. raise e
  46. from paddleslim.prune import Pruner
  47. from paddleslim.analysis import flops
  48. def main():
  49. cfg = load_config(FLAGS.config)
  50. merge_config(FLAGS.opt)
  51. check_config(cfg)
  52. check_version()
  53. main_arch = cfg.architecture
  54. # Use CPU for exporting inference model instead of GPU
  55. place = fluid.CPUPlace()
  56. exe = fluid.Executor(place)
  57. model = create(main_arch)
  58. startup_prog = fluid.Program()
  59. infer_prog = fluid.Program()
  60. with fluid.program_guard(infer_prog, startup_prog):
  61. with fluid.unique_name.guard():
  62. inputs_def = cfg['TestReader']['inputs_def']
  63. inputs_def['use_dataloader'] = False
  64. feed_vars, _ = model.build_inputs(**inputs_def)
  65. test_fetches = model.test(feed_vars)
  66. infer_prog = infer_prog.clone(True)
  67. exe.run(startup_prog)
  68. checkpoint.load_checkpoint(exe, infer_prog, cfg.weights)
  69. pruned_params = FLAGS.pruned_params
  70. assert (
  71. FLAGS.pruned_params is not None
  72. ), "FLAGS.pruned_params is empty!!! Please set it by '--pruned_params' option."
  73. pruned_params = FLAGS.pruned_params.strip().split(",")
  74. logger.info("pruned params: {}".format(pruned_params))
  75. pruned_ratios = [float(n) for n in FLAGS.pruned_ratios.strip().split(",")]
  76. logger.info("pruned ratios: {}".format(pruned_ratios))
  77. assert (len(pruned_params) == len(pruned_ratios)
  78. ), "The length of pruned params and pruned ratios should be equal."
  79. assert (pruned_ratios > [0] * len(pruned_ratios) and
  80. pruned_ratios < [1] * len(pruned_ratios)
  81. ), "The elements of pruned ratios should be in range (0, 1)."
  82. base_flops = flops(infer_prog)
  83. pruner = Pruner()
  84. infer_prog, _, _ = pruner.prune(
  85. infer_prog,
  86. fluid.global_scope(),
  87. params=pruned_params,
  88. ratios=pruned_ratios,
  89. place=place,
  90. only_graph=True)
  91. pruned_flops = flops(infer_prog)
  92. logger.info("pruned FLOPS: {}".format(
  93. float(base_flops - pruned_flops) / base_flops))
  94. dump_infer_config(FLAGS, cfg)
  95. save_infer_model(FLAGS, exe, feed_vars, test_fetches, infer_prog)
  96. if __name__ == '__main__':
  97. enable_static_mode()
  98. parser = ArgsParser()
  99. parser.add_argument(
  100. "--output_dir",
  101. type=str,
  102. default="output",
  103. help="Directory for storing the output model files.")
  104. parser.add_argument(
  105. "-p",
  106. "--pruned_params",
  107. default=None,
  108. type=str,
  109. help="The parameters to be pruned when calculating sensitivities.")
  110. parser.add_argument(
  111. "--pruned_ratios",
  112. default=None,
  113. type=str,
  114. help="The ratios pruned iteratively for each parameter when calculating sensitivities."
  115. )
  116. FLAGS = parser.parse_args()
  117. main()