load_model.py 7.8 KB

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