load_model.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. def load_model(model_dir, fixed_input_shape=None):
  24. model_scope = fluid.Scope()
  25. if not osp.exists(osp.join(model_dir, "model.yml")):
  26. raise Exception("There's not model.yml in {}".format(model_dir))
  27. with open(osp.join(model_dir, "model.yml")) as f:
  28. info = yaml.load(f.read(), Loader=yaml.Loader)
  29. if 'status' in info:
  30. status = info['status']
  31. elif 'save_method' in info:
  32. # 兼容老版本PaddleX
  33. status = info['save_method']
  34. if not hasattr(paddlex.cv.models, info['Model']):
  35. raise Exception("There's no attribute {} in paddlex.cv.models".format(
  36. info['Model']))
  37. if 'model_name' in info['_init_params']:
  38. del info['_init_params']['model_name']
  39. model = getattr(paddlex.cv.models, info['Model'])(**info['_init_params'])
  40. model.fixed_input_shape = fixed_input_shape
  41. if '_Attributes' in info:
  42. if 'fixed_input_shape' in info['_Attributes']:
  43. fixed_input_shape = info['_Attributes']['fixed_input_shape']
  44. if fixed_input_shape is not None:
  45. logging.info("Model already has fixed_input_shape with {}".
  46. format(fixed_input_shape))
  47. model.fixed_input_shape = fixed_input_shape
  48. with fluid.scope_guard(model_scope):
  49. if status == "Normal" or \
  50. status == "Prune" or status == "fluid.save":
  51. startup_prog = fluid.Program()
  52. model.test_prog = fluid.Program()
  53. with fluid.program_guard(model.test_prog, startup_prog):
  54. with fluid.unique_name.guard():
  55. model.test_inputs, model.test_outputs = model.build_net(
  56. mode='test')
  57. model.test_prog = model.test_prog.clone(for_test=True)
  58. model.exe.run(startup_prog)
  59. if status == "Prune":
  60. from .slim.prune import update_program
  61. model.test_prog = update_program(model.test_prog, model_dir,
  62. model.places[0])
  63. import pickle
  64. with open(osp.join(model_dir, 'model.pdparams'), 'rb') as f:
  65. load_dict = pickle.load(f)
  66. fluid.io.set_program_state(model.test_prog, load_dict)
  67. elif status == "Infer" or \
  68. status == "Quant" or status == "fluid.save_inference_model":
  69. [prog, input_names, outputs] = fluid.io.load_inference_model(
  70. model_dir, model.exe, params_filename='__params__')
  71. model.test_prog = prog
  72. test_outputs_info = info['_ModelInputsOutputs']['test_outputs']
  73. model.test_inputs = OrderedDict()
  74. model.test_outputs = OrderedDict()
  75. for name in input_names:
  76. model.test_inputs[name] = model.test_prog.global_block().var(
  77. name)
  78. for i, out in enumerate(outputs):
  79. var_desc = test_outputs_info[i]
  80. model.test_outputs[var_desc[0]] = out
  81. if 'Transforms' in info:
  82. transforms_mode = info.get('TransformsMode', 'RGB')
  83. # 固定模型的输入shape
  84. fix_input_shape(info, fixed_input_shape=fixed_input_shape)
  85. if transforms_mode == 'RGB':
  86. to_rgb = True
  87. else:
  88. to_rgb = False
  89. if 'BatchTransforms' in info:
  90. # 兼容老版本PaddleX模型
  91. model.test_transforms = build_transforms_v1(
  92. model.model_type, info['Transforms'], info['BatchTransforms'])
  93. model.eval_transforms = copy.deepcopy(model.test_transforms)
  94. else:
  95. model.test_transforms = build_transforms(model.model_type,
  96. info['Transforms'], to_rgb)
  97. model.eval_transforms = copy.deepcopy(model.test_transforms)
  98. if '_Attributes' in info:
  99. for k, v in info['_Attributes'].items():
  100. if k in model.__dict__:
  101. model.__dict__[k] = v
  102. logging.info("Model[{}] loaded.".format(info['Model']))
  103. model.scope = model_scope
  104. model.trainable = False
  105. model.status = status
  106. return model
  107. def fix_input_shape(info, fixed_input_shape=None):
  108. if fixed_input_shape is not None:
  109. resize = {'ResizeByShort': {}}
  110. padding = {'Padding': {}}
  111. if info['_Attributes']['model_type'] == 'classifier':
  112. pass
  113. else:
  114. resize['ResizeByShort']['short_size'] = min(fixed_input_shape)
  115. resize['ResizeByShort']['max_size'] = max(fixed_input_shape)
  116. padding['Padding']['target_size'] = list(fixed_input_shape)
  117. info['Transforms'].append(resize)
  118. info['Transforms'].append(padding)
  119. def build_transforms(model_type, transforms_info, to_rgb=True):
  120. if model_type == "classifier":
  121. import paddlex.cv.transforms.cls_transforms as T
  122. elif model_type == "detector":
  123. import paddlex.cv.transforms.det_transforms as T
  124. elif model_type == "segmenter":
  125. import paddlex.cv.transforms.seg_transforms as T
  126. transforms = list()
  127. for op_info in transforms_info:
  128. op_name = list(op_info.keys())[0]
  129. op_attr = op_info[op_name]
  130. if not hasattr(T, op_name):
  131. raise Exception(
  132. "There's no operator named '{}' in transforms of {}".format(
  133. op_name, model_type))
  134. transforms.append(getattr(T, op_name)(**op_attr))
  135. eval_transforms = T.Compose(transforms)
  136. eval_transforms.to_rgb = to_rgb
  137. return eval_transforms
  138. def build_transforms_v1(model_type, transforms_info, batch_transforms_info):
  139. """ 老版本模型加载,仅支持PaddleX前端导出的模型
  140. """
  141. logging.debug("Use build_transforms_v1 to reconstruct transforms")
  142. if model_type == "classifier":
  143. import paddlex.cv.transforms.cls_transforms as T
  144. elif model_type == "detector":
  145. import paddlex.cv.transforms.det_transforms as T
  146. elif model_type == "segmenter":
  147. import paddlex.cv.transforms.seg_transforms as T
  148. transforms = list()
  149. for op_info in transforms_info:
  150. op_name = op_info[0]
  151. op_attr = op_info[1]
  152. if op_name == 'DecodeImage':
  153. continue
  154. if op_name == 'Permute':
  155. continue
  156. if op_name == 'ResizeByShort':
  157. op_attr_new = dict()
  158. if 'short_size' in op_attr:
  159. op_attr_new['short_size'] = op_attr['short_size']
  160. else:
  161. op_attr_new['short_size'] = op_attr['target_size']
  162. op_attr_new['max_size'] = op_attr.get('max_size', -1)
  163. op_attr = op_attr_new
  164. if op_name.startswith('Arrange'):
  165. continue
  166. if not hasattr(T, op_name):
  167. raise Exception(
  168. "There's no operator named '{}' in transforms of {}".format(
  169. op_name, model_type))
  170. transforms.append(getattr(T, op_name)(**op_attr))
  171. if model_type == "detector" and len(batch_transforms_info) > 0:
  172. op_name = batch_transforms_info[0][0]
  173. op_attr = batch_transforms_info[0][1]
  174. assert op_name == "PaddingMiniBatch", "Only PaddingMiniBatch transform is supported for batch transform"
  175. padding = T.Padding(coarsest_stride=op_attr['coarsest_stride'])
  176. transforms.append(padding)
  177. eval_transforms = T.Compose(transforms)
  178. return eval_transforms