export_serving_model.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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__, *(['..'] * 2)))
  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. from ppdet.utils.check import check_config, check_version, enable_static_mode
  32. import ppdet.utils.checkpoint as checkpoint
  33. from ppdet.utils.export_utils import dump_infer_config, prune_feed_vars
  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. def save_serving_model(FLAGS, exe, feed_vars, test_fetches, infer_prog):
  47. cfg_name = os.path.basename(FLAGS.config).split('.')[0]
  48. save_dir = os.path.join(FLAGS.output_dir, cfg_name)
  49. feed_var_names = [var.name for var in feed_vars.values()]
  50. fetch_list = sorted(test_fetches.items(), key=lambda i: i[0])
  51. target_vars = [var[1] for var in fetch_list]
  52. feed_var_names = prune_feed_vars(feed_var_names, target_vars, infer_prog)
  53. serving_client = os.path.join(FLAGS.output_dir, 'serving_client')
  54. serving_server = os.path.join(FLAGS.output_dir, 'serving_server')
  55. logger.info(
  56. "Export serving model to {}, client side: {}, server side: {}. input: {}, output: "
  57. "{}...".format(FLAGS.output_dir, serving_client, serving_server,
  58. feed_var_names, [str(var.name) for var in target_vars]))
  59. feed_dict = {x: infer_prog.global_block().var(x) for x in feed_var_names}
  60. fetch_dict = {x.name: x for x in target_vars}
  61. import paddle_serving_client.io as serving_io
  62. serving_client = os.path.join(save_dir, 'serving_client')
  63. serving_server = os.path.join(save_dir, 'serving_server')
  64. serving_io.save_model(
  65. client_config_folder=serving_client,
  66. server_model_folder=serving_server,
  67. feed_var_dict=feed_dict,
  68. fetch_var_dict=fetch_dict,
  69. main_program=infer_prog)
  70. def main():
  71. cfg = load_config(FLAGS.config)
  72. merge_config(FLAGS.opt)
  73. check_config(cfg)
  74. check_version()
  75. main_arch = cfg.architecture
  76. # Use CPU for exporting inference model instead of GPU
  77. place = fluid.CPUPlace()
  78. exe = fluid.Executor(place)
  79. model = create(main_arch)
  80. startup_prog = fluid.Program()
  81. infer_prog = fluid.Program()
  82. with fluid.program_guard(infer_prog, startup_prog):
  83. with fluid.unique_name.guard():
  84. inputs_def = cfg['TestReader']['inputs_def']
  85. inputs_def['use_dataloader'] = False
  86. feed_vars, _ = model.build_inputs(**inputs_def)
  87. test_fetches = model.test(feed_vars)
  88. infer_prog = infer_prog.clone(True)
  89. exe.run(startup_prog)
  90. checkpoint.load_params(exe, infer_prog, cfg.weights)
  91. save_serving_model(FLAGS, exe, feed_vars, test_fetches, infer_prog)
  92. dump_infer_config(FLAGS, cfg)
  93. if __name__ == '__main__':
  94. enable_static_mode()
  95. parser = ArgsParser()
  96. parser.add_argument(
  97. "--output_dir",
  98. type=str,
  99. default="output",
  100. help="Directory for storing the output model files.")
  101. FLAGS = parser.parse_args()
  102. main()