load_model.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  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. import yaml
  15. import os.path as osp
  16. import six
  17. import copy
  18. from collections import OrderedDict
  19. import paddle.fluid as fluid
  20. from paddle.fluid.framework import Parameter
  21. import paddlex
  22. import paddlex.utils.logging as logging
  23. from paddlex.cv.transforms import build_transforms, build_transforms_v1
  24. def load_model(model_dir, fixed_input_shape=None):
  25. model_scope = fluid.Scope()
  26. if not osp.exists(model_dir):
  27. logging.error("model_dir '{}' is not exists!".format(model_dir))
  28. if not osp.exists(osp.join(model_dir, "model.yml")):
  29. raise Exception("There's not model.yml in {}".format(model_dir))
  30. with open(osp.join(model_dir, "model.yml")) as f:
  31. info = yaml.load(f.read(), Loader=yaml.Loader)
  32. if 'status' in info:
  33. status = info['status']
  34. elif 'save_method' in info:
  35. # 兼容老版本PaddleX
  36. status = info['save_method']
  37. if not hasattr(paddlex.cv.models, info['Model']):
  38. raise Exception("There's no attribute {} in paddlex.cv.models".format(
  39. info['Model']))
  40. if 'model_name' in info['_init_params']:
  41. del info['_init_params']['model_name']
  42. model = getattr(paddlex.cv.models, info['Model'])(**info['_init_params'])
  43. model.fixed_input_shape = fixed_input_shape
  44. if '_Attributes' in info:
  45. if 'fixed_input_shape' in info['_Attributes']:
  46. fixed_input_shape = info['_Attributes']['fixed_input_shape']
  47. if fixed_input_shape is not None:
  48. logging.info("Model already has fixed_input_shape with {}".
  49. format(fixed_input_shape))
  50. model.fixed_input_shape = fixed_input_shape
  51. with fluid.scope_guard(model_scope):
  52. if status == "Normal" or \
  53. status == "Prune" or status == "fluid.save":
  54. startup_prog = fluid.Program()
  55. model.test_prog = fluid.Program()
  56. with fluid.program_guard(model.test_prog, startup_prog):
  57. with fluid.unique_name.guard():
  58. model.test_inputs, model.test_outputs = model.build_net(
  59. mode='test')
  60. model.test_prog = model.test_prog.clone(for_test=True)
  61. model.exe.run(startup_prog)
  62. if status == "Prune":
  63. from .slim.prune import update_program
  64. model.test_prog = update_program(model.test_prog, model_dir,
  65. model.places[0])
  66. import pickle
  67. with open(osp.join(model_dir, 'model.pdparams'), 'rb') as f:
  68. load_dict = pickle.load(f)
  69. fluid.io.set_program_state(model.test_prog, load_dict)
  70. elif status == "Infer" or \
  71. status == "Quant" or status == "fluid.save_inference_model":
  72. [prog, input_names, outputs] = fluid.io.load_inference_model(
  73. model_dir, model.exe, params_filename='__params__')
  74. model.test_prog = prog
  75. test_outputs_info = info['_ModelInputsOutputs']['test_outputs']
  76. model.test_inputs = OrderedDict()
  77. model.test_outputs = OrderedDict()
  78. for name in input_names:
  79. model.test_inputs[name] = model.test_prog.global_block().var(
  80. name)
  81. for i, out in enumerate(outputs):
  82. var_desc = test_outputs_info[i]
  83. model.test_outputs[var_desc[0]] = out
  84. if 'Transforms' in info:
  85. transforms_mode = info.get('TransformsMode', 'RGB')
  86. # 固定模型的输入shape
  87. fix_input_shape(info, fixed_input_shape=fixed_input_shape)
  88. if transforms_mode == 'RGB':
  89. to_rgb = True
  90. else:
  91. to_rgb = False
  92. if 'BatchTransforms' in info:
  93. # 兼容老版本PaddleX模型
  94. model.test_transforms = build_transforms_v1(
  95. model.model_type, info['Transforms'], info['BatchTransforms'])
  96. model.eval_transforms = copy.deepcopy(model.test_transforms)
  97. else:
  98. model.test_transforms = build_transforms(model.model_type,
  99. info['Transforms'], to_rgb)
  100. model.eval_transforms = copy.deepcopy(model.test_transforms)
  101. if '_Attributes' in info:
  102. for k, v in info['_Attributes'].items():
  103. if k in model.__dict__:
  104. model.__dict__[k] = v
  105. logging.info("Model[{}] loaded.".format(info['Model']))
  106. model.scope = model_scope
  107. model.trainable = False
  108. model.status = status
  109. return model
  110. def fix_input_shape(info, fixed_input_shape=None):
  111. if fixed_input_shape is not None:
  112. resize = {'ResizeByShort': {}}
  113. padding = {'Padding': {}}
  114. if info['_Attributes']['model_type'] == 'classifier':
  115. pass
  116. else:
  117. resize['ResizeByShort']['short_size'] = min(fixed_input_shape)
  118. resize['ResizeByShort']['max_size'] = max(fixed_input_shape)
  119. padding['Padding']['target_size'] = list(fixed_input_shape)
  120. info['Transforms'].append(resize)
  121. info['Transforms'].append(padding)