export_utils.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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 yaml
  19. from collections import OrderedDict
  20. import paddle
  21. from ppdet.data.source.category import get_categories
  22. from ppdet.utils.logger import setup_logger
  23. logger = setup_logger('ppdet.engine')
  24. # Global dictionary
  25. TRT_MIN_SUBGRAPH = {
  26. 'YOLO': 3,
  27. 'SSD': 60,
  28. 'RCNN': 40,
  29. 'RetinaNet': 40,
  30. 'S2ANet': 80,
  31. 'EfficientDet': 40,
  32. 'Face': 3,
  33. 'TTFNet': 60,
  34. 'FCOS': 16,
  35. 'SOLOv2': 60,
  36. 'HigherHRNet': 3,
  37. 'HRNet': 3,
  38. 'DeepSORT': 3,
  39. 'ByteTrack': 10,
  40. 'JDE': 10,
  41. 'FairMOT': 5,
  42. 'GFL': 16,
  43. 'PicoDet': 3,
  44. 'CenterNet': 5,
  45. 'TOOD': 5,
  46. 'YOLOX': 8,
  47. }
  48. KEYPOINT_ARCH = ['HigherHRNet', 'TopDownHRNet']
  49. MOT_ARCH = ['DeepSORT', 'JDE', 'FairMOT', 'ByteTrack']
  50. def _prune_input_spec(input_spec, program, targets):
  51. # try to prune static program to figure out pruned input spec
  52. # so we perform following operations in static mode
  53. device = paddle.get_device()
  54. paddle.enable_static()
  55. paddle.set_device(device)
  56. pruned_input_spec = [{}]
  57. program = program.clone()
  58. program = program._prune(targets=targets)
  59. global_block = program.global_block()
  60. for name, spec in input_spec[0].items():
  61. try:
  62. v = global_block.var(name)
  63. pruned_input_spec[0][name] = spec
  64. except Exception:
  65. pass
  66. paddle.disable_static(place=device)
  67. return pruned_input_spec
  68. def _parse_reader(reader_cfg, dataset_cfg, metric, arch, image_shape):
  69. preprocess_list = []
  70. anno_file = dataset_cfg.get_anno()
  71. clsid2catid, catid2name = get_categories(metric, anno_file, arch)
  72. label_list = [str(cat) for cat in catid2name.values()]
  73. fuse_normalize = reader_cfg.get('fuse_normalize', False)
  74. sample_transforms = reader_cfg['sample_transforms']
  75. for st in sample_transforms[1:]:
  76. for key, value in st.items():
  77. p = {'type': key}
  78. if key == 'Resize':
  79. if int(image_shape[1]) != -1:
  80. value['target_size'] = image_shape[1:]
  81. if fuse_normalize and key == 'NormalizeImage':
  82. continue
  83. p.update(value)
  84. preprocess_list.append(p)
  85. batch_transforms = reader_cfg.get('batch_transforms', None)
  86. if batch_transforms:
  87. for bt in batch_transforms:
  88. for key, value in bt.items():
  89. # for deploy/infer, use PadStride(stride) instead PadBatch(pad_to_stride)
  90. if key == 'PadBatch':
  91. preprocess_list.append({
  92. 'type': 'PadStride',
  93. 'stride': value['pad_to_stride']
  94. })
  95. break
  96. return preprocess_list, label_list
  97. def _parse_tracker(tracker_cfg):
  98. tracker_params = {}
  99. for k, v in tracker_cfg.items():
  100. tracker_params.update({k: v})
  101. return tracker_params
  102. def _dump_infer_config(config, path, image_shape, model):
  103. arch_state = False
  104. from ppdet.core.config.yaml_helpers import setup_orderdict
  105. setup_orderdict()
  106. use_dynamic_shape = True if image_shape[2] == -1 else False
  107. infer_cfg = OrderedDict({
  108. 'mode': 'paddle',
  109. 'draw_threshold': 0.5,
  110. 'metric': config['metric'],
  111. 'use_dynamic_shape': use_dynamic_shape
  112. })
  113. export_onnx = config.get('export_onnx', False)
  114. infer_arch = config['architecture']
  115. if 'RCNN' in infer_arch and export_onnx:
  116. logger.warning(
  117. "Exporting RCNN model to ONNX only support batch_size = 1")
  118. infer_cfg['export_onnx'] = True
  119. if infer_arch in MOT_ARCH:
  120. if infer_arch == 'DeepSORT':
  121. tracker_cfg = config['DeepSORTTracker']
  122. else:
  123. tracker_cfg = config['JDETracker']
  124. infer_cfg['tracker'] = _parse_tracker(tracker_cfg)
  125. for arch, min_subgraph_size in TRT_MIN_SUBGRAPH.items():
  126. if arch in infer_arch:
  127. infer_cfg['arch'] = arch
  128. infer_cfg['min_subgraph_size'] = min_subgraph_size
  129. arch_state = True
  130. break
  131. if infer_arch == 'YOLOX':
  132. infer_cfg['arch'] = infer_arch
  133. infer_cfg['min_subgraph_size'] = TRT_MIN_SUBGRAPH[infer_arch]
  134. arch_state = True
  135. if not arch_state:
  136. logger.error(
  137. 'Architecture: {} is not supported for exporting model now.\n'.
  138. format(infer_arch) +
  139. 'Please set TRT_MIN_SUBGRAPH in ppdet/engine/export_utils.py')
  140. os._exit(0)
  141. if 'mask_head' in config[config['architecture']] and config[config[
  142. 'architecture']]['mask_head']:
  143. infer_cfg['mask'] = True
  144. label_arch = 'detection_arch'
  145. if infer_arch in KEYPOINT_ARCH:
  146. label_arch = 'keypoint_arch'
  147. if infer_arch in MOT_ARCH:
  148. label_arch = 'mot_arch'
  149. reader_cfg = config['TestMOTReader']
  150. dataset_cfg = config['TestMOTDataset']
  151. else:
  152. reader_cfg = config['TestReader']
  153. dataset_cfg = config['TestDataset']
  154. infer_cfg['Preprocess'], infer_cfg['label_list'] = _parse_reader(
  155. reader_cfg, dataset_cfg, config['metric'], label_arch, image_shape[1:])
  156. if infer_arch == 'PicoDet':
  157. if hasattr(config, 'export') and config['export'].get(
  158. 'post_process',
  159. False) and not config['export'].get('benchmark', False):
  160. infer_cfg['arch'] = 'GFL'
  161. head_name = 'PicoHeadV2' if config['PicoHeadV2'] else 'PicoHead'
  162. infer_cfg['NMS'] = config[head_name]['nms']
  163. # In order to speed up the prediction, the threshold of nms
  164. # is adjusted here, which can be changed in infer_cfg.yml
  165. config[head_name]['nms']["score_threshold"] = 0.3
  166. config[head_name]['nms']["nms_threshold"] = 0.5
  167. infer_cfg['fpn_stride'] = config[head_name]['fpn_stride']
  168. yaml.dump(infer_cfg, open(path, 'w'))
  169. logger.info("Export inference config file to {}".format(os.path.join(path)))