load_model.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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. 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. if info['Model'].count('RCNN') > 0:
  52. if info['_init_params']['with_fpn']:
  53. if model.fixed_input_shape[0] % 32 > 0:
  54. raise Exception(
  55. "The first value in fixed_input_shape must be a multiple of 32, but recieved {}.".
  56. format(model.fixed_input_shape[0]))
  57. if model.fixed_input_shape[1] % 32 > 0:
  58. raise Exception(
  59. "The second value in fixed_input_shape must be a multiple of 32, but recieved {}.".
  60. format(model.fixed_input_shape[1]))
  61. with fluid.scope_guard(model_scope):
  62. if status == "Normal" or \
  63. status == "Prune" or status == "fluid.save":
  64. startup_prog = fluid.Program()
  65. model.test_prog = fluid.Program()
  66. with fluid.program_guard(model.test_prog, startup_prog):
  67. with fluid.unique_name.guard():
  68. model.test_inputs, model.test_outputs = model.build_net(
  69. mode='test')
  70. model.test_prog = model.test_prog.clone(for_test=True)
  71. model.exe.run(startup_prog)
  72. if status == "Prune":
  73. from .slim.prune import update_program
  74. model.test_prog = update_program(
  75. model.test_prog,
  76. model_dir,
  77. model.places[0],
  78. scope=model_scope)
  79. import pickle
  80. with open(osp.join(model_dir, 'model.pdparams'), 'rb') as f:
  81. load_dict = pickle.load(f)
  82. fluid.io.set_program_state(model.test_prog, load_dict)
  83. elif status == "Infer" or \
  84. status == "Quant" or status == "fluid.save_inference_model":
  85. [prog, input_names, outputs] = fluid.io.load_inference_model(
  86. model_dir, model.exe, params_filename='__params__')
  87. model.test_prog = prog
  88. test_outputs_info = info['_ModelInputsOutputs']['test_outputs']
  89. model.test_inputs = OrderedDict()
  90. model.test_outputs = OrderedDict()
  91. for name in input_names:
  92. model.test_inputs[name] = model.test_prog.global_block().var(
  93. name)
  94. for i, out in enumerate(outputs):
  95. var_desc = test_outputs_info[i]
  96. model.test_outputs[var_desc[0]] = out
  97. if 'Transforms' in info:
  98. transforms_mode = info.get('TransformsMode', 'RGB')
  99. # 固定模型的输入shape
  100. fix_input_shape(info, fixed_input_shape=model.fixed_input_shape)
  101. if transforms_mode == 'RGB':
  102. to_rgb = True
  103. else:
  104. to_rgb = False
  105. if 'BatchTransforms' in info:
  106. # 兼容老版本PaddleX模型
  107. model.test_transforms = build_transforms_v1(
  108. model.model_type, info['Transforms'], info['BatchTransforms'])
  109. model.eval_transforms = copy.deepcopy(model.test_transforms)
  110. else:
  111. model.test_transforms = build_transforms(
  112. model.model_type, info['Transforms'], to_rgb)
  113. model.eval_transforms = copy.deepcopy(model.test_transforms)
  114. if '_Attributes' in info:
  115. for k, v in info['_Attributes'].items():
  116. if k in model.__dict__:
  117. model.__dict__[k] = v
  118. logging.info("Model[{}] loaded.".format(info['Model']))
  119. model.scope = model_scope
  120. model.trainable = False
  121. model.status = status
  122. return model
  123. def fix_input_shape(info, fixed_input_shape=None):
  124. if fixed_input_shape is not None:
  125. input_channel = 3
  126. if 'input_channel' in info['_init_params']:
  127. input_channel = info['_init_params']['input_channel']
  128. resize = {'ResizeByShort': {}}
  129. padding = {'Padding': {}}
  130. if info['_Attributes']['model_type'] == 'classifier':
  131. pass
  132. elif info['Model'].count('YOLO') > 0:
  133. resize_op_index = None
  134. for i in range(len(info['Transforms'])):
  135. if list(info['Transforms'][i].keys())[0] == 'Resize':
  136. resize_op_index = i
  137. if resize_op_index is not None:
  138. info['Transforms'][resize_op_index]['Resize'][
  139. 'target_size'] = fixed_input_shape[0]
  140. elif info['Model'].count('RCNN') > 0:
  141. resize_op_index = None
  142. for i in range(len(info['Transforms'])):
  143. if list(info['Transforms'][i].keys())[0] == 'ResizeByShort':
  144. resize_op_index = i
  145. if resize_op_index is not None:
  146. info['Transforms'][resize_op_index]['ResizeByShort'][
  147. 'short_size'] = min(fixed_input_shape)
  148. info['Transforms'][resize_op_index]['ResizeByShort'][
  149. 'max_size'] = max(fixed_input_shape)
  150. else:
  151. resize['ResizeByShort']['short_size'] = min(fixed_input_shape)
  152. resize['ResizeByShort']['max_size'] = max(fixed_input_shape)
  153. info['Transforms'].append(resize)
  154. padding_op_index = None
  155. for i in range(len(info['Transforms'])):
  156. if list(info['Transforms'][i].keys())[0] == 'Padding':
  157. padding_op_index = i
  158. if padding_op_index is not None:
  159. info['Transforms'][padding_op_index]['Padding'][
  160. 'target_size'] = list(fixed_input_shape)
  161. else:
  162. padding['Padding']['target_size'] = list(fixed_input_shape)
  163. info['Transforms'].append(padding)
  164. elif info['_Attributes']['model_type'] == 'segmenter':
  165. resize['ResizeByShort']['short_size'] = min(fixed_input_shape)
  166. resize['ResizeByShort']['max_size'] = max(fixed_input_shape)
  167. padding['Padding']['target_size'] = list(fixed_input_shape)
  168. padding['Padding']['im_padding_value'] = [0.] * input_channel
  169. info['Transforms'].append(resize)
  170. info['Transforms'].append(padding)